View Source Embed tweets

You'll notice that embedded tweets generated by https://publish.twitter.com usually won't render correctly on your pages, and that's due to the fact that the client JavaScript used to load such tweets is executed asyncly along with the LiveView rendering process, causing it to be executed too early. To fix this, we need to load the tweets after LiveView has finished rendering the page.

Steps

1. Load the Twitter JS script

Find the Layout you're using on the pages where you're embedding tweets, then edit its template to include the following script:

<script>
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));

window.addEventListener("phx:page-loading-stop", function(info){
  twttr.widgets.load()
});
</script>

This will first include the global twttr object and then load the tweets as soon as LiveView has finished rendering the page.

Visit https://developer.x.com/en/docs/x-for-websites/javascript-api/guides/set-up-twitter-for-websites for more info.

2. Embed tweets

Now you can embed tweets on your pages but remember to remove the <script> that's included at the end of the embedded code, as we're already loading the Twitter JS script in the Layout template.

Usually it looks like this:

<blockquote class="twitter-tweet" data-theme="dark">><!-- content omitted --></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

Remove the <script> tag at the end of the embedded tweet to look like this:

<blockquote class="twitter-tweet" data-theme="dark">><!-- content omitted --></blockquote>