8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

turbolinksでtwitterのtimelineを期待通り表示させる

Last updated at Posted at 2014-10-13

期待通りに動作させるまで苦労したので、ここで共有します。

問題

  1. 戻るボタンを押すと、ツイッターのタイムラインが空欄になっている。
  2. 戻るボタンを押しても空欄にならなくなったが、ページロード時にタイムラインが表示されない。

問題を解決したコード

参考リンクの1番目をお手本にしています。

app/views/layouts/application.html.erb
- <a class="twitter-timeline" 
-   href="https://twitter.com/twitterapi" 
-   data-widget-id="YOUR-WIDGET-ID">Tweets by @twitterapi
- </a>

+ <div class="twiiter-timeline-container" 
+   data-widget-id="YOUR-WIDGET-ID" 
+   data-widget-options="<%= { borderColor: '#abcdef' }.to_json %>">
+ </div>

aで与えられていた情報を元に、タイムラインを表示したい場所へ上記のdivを配置します。

app/assets/javascripts/twitter.js.coffee
$ ->
  loadTwitterSDK()
  $(document).on 'page:change', renderTimelines

loadTwitterSDK = ->
  $.getScript "//platform.twitter.com/widgets.js", ->
    renderTimelines()

renderTimelines = ->
  $('.twitter-timeline-container').each ->
    $container = $(this)
    widgetId = $container.data 'widget-id'
    widgetOptions = $container.data 'widget-options'
    $container.empty()
    twttr?.widgets.createTimeline widgetId, $container[0], null, widgetOptions

解説

  1. 戻るボタンを押すと、ツイッターのタイムラインが空欄になっている。
    $(document).on 'page:change'をトリガーにしてdivにタイムラインを表示させました。

  2. 戻るボタンを押しても空欄にならなくなったが、ページロード時にタイムラインが表示されない。
    getScriptsの後にタイムラインを読み込ませました。

誰かの参考になれば幸いです。

参考

https://github.com/reed/turbolinks-compatibility/issues/22
http://semooh.jp/jquery/api/ajax/jQuery.getScript/+url,+callback+/
http://reed.github.io/turbolinks-compatibility/twitter.html

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?