3
3

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 1 year has passed since last update.

twitterの埋め込みを軽くする

Posted at

埋め込むとけっこう重たいみたいですが、調べてもwidgets.jsを読み込むスクリプトタグを後から追加くらいしか見当たらなかったのでメモとして書きます。

前提となる技術

IntersectionObserverを使います。IEがさよならバイバイしたので便利な世の中になりました。

コードスニペット

<!-- 埋め込みのコピペ、aタグのclass属性の中身を変えて埋め込みが実行されないようにしてある -->
<a class="pre-twitter-timeline" data-height="500" href="https://twitter.com/elonmusk?ref_src=twsrc%5Etfw">Tweets by elonmusk</a>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<!-- IntersectionObserverを使い、見えるようになったらaタグのclass属性を正しいものにして埋め込みを実行 --><script type="text/javascript">
  const elm = document.querySelector('a.pre-twitter-timeline');
  const observer = new IntersectionObserver((entries) => {
    if (!entries[0].isIntersecting) return;
    observer.unobserve(elm);
    elm.classList.remove('pre-twitter-timeline');
    elm.classList.add('twitter-timeline');
    twttr.widgets.load();
  });
  observer.observe(elm);
</script>

参考

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?