I'm trying to include the twitter widget script for better performance of displaying embedded tweets in my Rails 5 application (code given here: https://dev.twitter.com/web/javascript/loading)
function twitterWidget() {
alert("twitter");
window.twttr = (function (d, s, id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src= "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } });
}(document, "script", "twitter-wjs"));
};
$(document).on('turbolinks:load', twitterWidget);
This works fine unless on first page visit (the script runs - thus showing me the alert - but the tweet is not properly displayed).
Edit: The code above will work if I directly call the page but not when I use a link_to
from another page. Then it only works on refreshing the same page again.
I disabled Turbolinks and it works fine, however I want to keep using Turbolinks for faster page loading.
Is there a solution for this by selectively disabling turbolinks for just this widget?
Thanks for your help!
Thanks to help by a colleague I found the solution to the problem.
The main issue is that turbolinks doesn't run content in the head so one needs to insert the twitter script into the body of the page. Changing the script like the following has worked for me:
function twitterWidget() {
window.twttr = (function (d, s, id) {
var t, js, fjs = $("body");
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src= "https://platform.twitter.com/widgets.js";
$(fjs).append(js, fjs);
return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } });
}(document, "script", "twitter-wjs"));
};
$(document).on('turbolinks:load', twitterWidget);
Hope this will help someone!