LoginSignup
0
1

More than 1 year has passed since last update.

FIDを改善するためにサードパーティ製のコードを遅延読み込み

Last updated at Posted at 2022-07-04

はじめに

SEO対策としてCoreWebVitalの改善をするためにPageSpeedInsightやlighthouseで調査していると、JavaScriptの削減を提案されることがある。
サードパーティ製のスクリプトを使用しており、削減できなかったので遅延読み込みで対応してみた。

Youtubeを遅延読み込み

今回は lazysizes を使用して、Youtube Iframe API のリクエストを遅延読み込みする。
具体的には、lazysizesがlazybeforeunveilイベントを発火するので、これを受け取ったらYoutubeIframeAPIにリクエストを送り、指定したidのdivタグをyoutubeの埋め込みiframeタグに変換する。

<html>
  <head>
...
    <script src="lazysizes.min.js" async></script>
...
  </head>

  <body>
...
    <div class="lazyload">
        <div id="player1"></div>
    </div>

    <div class="lazyload">
        <div id="player2"></div>
    </div>
...

    <footer>
...
        <script>
            var ytData = [
                {div_id:"player1", video_id:"hogehoge"},
                {div_id:"player2", video_id:"fugafuga"}
            ];
            var ytPlayer = [];
            var player;
            var ytEvent = {
                "onReady": function (event) {
                    ytPlayer[ytPlayer.length] = event.target
                }
            };

            var tag = document.createElement('script');
            tag.src = "https://www.youtube.com/iframe_api";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

            function onYouTubeIframeAPIReadyLazyLoad(div_id) {
                var data = ytData.filter(function(value) {
                    return value.div_id == div_id;
                });

                player = new YT.Player(data[0]['div_id'], {
                    height: 360,
                    width: 100%,
                    videoId: data[0]['video_id'],
                    events: ytEvent,
                    playerVars: {
                        loop: 10,
                        rel: 0,
                        playsinline: 1,
                        controls: 0,
                        showinfo: 0,
                        playlist: data[0]['video_id'],
                        origin: location.protocol + '//' + location.hostname + "/"
                    }
                }); 
            }

            document.addEventListener("lazybeforeunveil", function(e) {
                    var childElementId = e.target.firstElementChild.id;
                    onYouTubeIframeAPIReadyLazyLoad(childElementId)
            })
        </script>
...
    </footer>
  </body>
</html>

結果

変更前後をLighthouseで計測。
TBTが 280ms → 80ms (FIDはLighthouseで計測できないため、TBTで代用)、
Speed Indexが 3.8s → 1.8s に改善した。

lazyloadは画像のみ適応できると思い込んでいたので、使い所によってはもっと改善できそう。

0
1
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
0
1