Turbolinks 5.0 and Facebook SDK

前端 未结 3 781
南旧
南旧 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:19

    Here is a way to integrate Turbolinks 5 with Facebook SDK.

    In your layout template:

    // /source/layouts/layout.erb
    
      <%= yield %>
      

    Then in your javascript using jQuery here:

    function FBInit() {
      FB.init({
        appId      : 'YOUR_KEY',
        xfbml      : true,
        version    : 'v2.8'
      });
      $('#permanent').append( $('#fb-root').detach() );
    };
    
    $(document).ready(function(){
      $.getScript( "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.8", FBInit);
    });
    
    $(document).on('turbolinks:load', function(event){
      if (typeof FB !== "undefined" && FB !== null) {
        FB.XFBML.parse();
      }
    });
    
    $(document).on("turbolinks:before-cache", function() {
        $('[data-turbolinks-no-cache]').remove();
    });
    

    Then use any Facebook plugins using the data-turbolinks-no-cache attribute like this:

    Here is the gist and here is a blog post explaining how it works

提交回复
热议问题