Turbolinks 5.0 and Facebook SDK

前端 未结 3 772
南旧
南旧 2021-02-11 06:31

Last week I upgraded to Rails 5 which is using Turbolinks 5.0. I used the following script to load the Facebook like button with Turbolinks 3.0:

3条回答
  •  终归单人心
    2021-02-11 07:15

    If you prefer to use native Turbolinks 5 events, you can add this script to your Rails assets:

    // FacebookSDK
    // https://developers.facebook.com/docs/plugins/page-plugin/
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s);
      js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.8";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk')); // Replace 'facebook-jssdk' with your page id.
    
    // Compatibility with Turbolinks 5
    (function($) {
      var fbRoot;
    
      function saveFacebookRoot() {
        if ($('#fb-root').length) {
          fbRoot = $('#fb-root').detach();
        }
      };
    
      function restoreFacebookRoot() {
        if (fbRoot != null) {
          if ($('#fb-root').length) {
            $('#fb-root').replaceWith(fbRoot);
          } else {
            $('body').append(fbRoot);
          }
        }
    
        if (typeof FB !== "undefined" && FB !== null) { // Instance of FacebookSDK
          FB.XFBML.parse();
        }
      };
    
      document.addEventListener('turbolinks:request-start', saveFacebookRoot)
      document.addEventListener('turbolinks:load', restoreFacebookRoot)
    }(jQuery));
    

    From: https://gist.github.com/6temes/52648dc6b3adbbf05da3942794b97a00

提交回复
热议问题