ADZ 學習筆記

Ruby/Rails, Startup, Life

Rails 筆記 - turbolinks + facebook share button

| Comments

前幾天幫網站加入 facebook share button 時,發現 trubolinks + facebook 官方提供的 sample code 會有問題。

(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/zh_TW/all.js#xfbml=1&appId=426504790814978";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

因為 trubolinks 不會重新 render 頁面加上 facebook 的 sample code 是在網頁載入時才去非同步 download 一隻 js 來處理頁面上所有的 facebook plugin。

找到的解法

facebook.coffee
fb_root = null
fb_events_bound = false

$ ->
  loadFacebookSDK()
  bindFacebookEvents() unless fb_events_bound

bindFacebookEvents = ->
  $(document)
    .on('page:fetch', saveFacebookRoot)
    .on('page:change', restoreFacebookRoot)
    .on('page:load', ->
      FB?.XFBML.parse()
    )
  fb_events_bound = true

saveFacebookRoot = ->
  fb_root = $('#fb-root').detach()

restoreFacebookRoot = ->
  if $('#fb-root').length > 0
    $('#fb-root').replaceWith fb_root
  else
    $('body').append fb_root

loadFacebookSDK = ->
  window.fbAsyncInit = initializeFacebookSDK
  $.getScript("//connect.facebook.net/zh_TW/all.js#xfbml=1")

initializeFacebookSDK = ->
  FB.init
    appId     : 'TOKEN HERE'
    channelUrl: '//YOUR_DOMAIN_HERE/PATH/TO/channel.html'
    status    : true
    cookie    : true
    xfbml     : true

http://reed.github.io/turbolinks-compatibility/facebook.html

增加 facebook social plugin 效能

方法一、ruby 實作 channel.html
app/controller/some_controller.rb
class SomeController < ApplicationController
  caches_page :some_action
  
    def some_action
    cache_expire = 1.year
      response.headers["Pragma"] = "public"
    response.headers["Cache-Control"] = "max-age=#{cache_expire.to_i}"
      response.headers["Expires"] = (Time.now + cache_expire).strftime("%d %m %Y %H:%I:%S %Z")
      render :layout => false, :inline => "<script src='//connect.facebook.net/zh_TW/all.js'></script>"
    end
end
方法二、 直接開一個檔案在 public/ 底下
public/channel.html
<script src='//connect.facebook.net/zh_TW/all.js'></script>

然後,再去 web server 上設定 static file browser cache 參數即可。

https://developers.facebook.com/blog/post/2011/08/02/how-to--optimize-social-plugin-performance/

Comments

comments powered by Disqus