LoginSignup
0
0

More than 3 years have passed since last update.

vue.jsでIntersection Observerを使って画像遅延を行う

Last updated at Posted at 2021-01-30

背景

作成したサイトがSearchConsoleで『改善が必要』との指摘をされた。
画像表示の遅さが原因のひとつであるためIntersection Observerを使って画像遅延読みこみすることにより改善をはかる

実施したこと

html

  • 対象の画像にrefを設定する
  • srcにダミー画像を設定
  • data-srcに表示したい画像を設定する  content_info.eyecatch_img_urlには表示したい画像のパスを入れる
<img class = "index_img" ref="index_imgs" src = "/img/no_img2.png" v-bind:data-src = "content_info.eyecatch_img_url">

javascript

  • 対象画像が表示範囲に入った場合の処理を"if (entry.isIntersecting)"ないに記述...(a)
  • 下記はsrcにdata-srcを代入する...(b)
  • 監視を解除する...(c)
  • 監視を設定する...(d)
    var content_table = new Vue({
        el: "#index_content_list",
           ...中略....
        },
        mounted: function(){
            if ("IntersectionObserver" in window) {
                var observer1 = new IntersectionObserver(entries => {
                    entries.forEach(function(entry) {
                        if (entry.isIntersecting) { ...(a)
                            let lazyImage = entry.target;
                            lazyImage.src = lazyImage.dataset.src; ...(b)
                            observer1.unobserve(lazyImage); ...(c)
                        }
                    })
                })
                const observe_elements = this.$refs.index_imgs;  
                observe_elements.forEach(function(lazyImage) {
                    observer1.observe(lazyImage); ...(d)
                });
            }
        },
    })

残件

Intersection Observerがサポートされていないブラウザへの対処
polyfillを使った処理を追加する

if ("IntersectionObserver" in window) {
    ...上記
}else{
    ...polyfillを追加
}

オプションの解説

IntersectionObserver APIのオプション解説

参考

vue.jsで無限スクロール(infinite scrolling)
SEOを考慮したGoogle推奨の画像の遅延読み込み処理まとめ

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