ロゴテキスト ロゴ

    NuxtでLazy Loadを使う

    NuxtでLazy Loadを使う

    Nuxtのプロジェクトで画像などのリソースに対してLazyLoadを設定してみます。

    検証した環境

    1 nuxt 2.14.3
    2 nuxt-lazy-load 1.2.4

    ライブラリの導入

    NuxtでLazy Loadを実装するためのライブラリをインストールします

    nuxt-lazy-load - npm

    $ yarn add nuxt-lazy-load

    nuxt.config.jsに設定

    nuxt.config.jsに使用するための設定を追記します

    nuxt.config.js
    export default {
      modules: [
        'nuxt-lazy-load'
      ]
      ・・・

    オプションを設定する事が出来るため、オプションを設定する場合は配列で渡します

    nuxt.config.js
    export default {
      modules: [
        ['nuxt-lazy-load', {
            // Your options
        }]
      ]
      ・・・


    公式のREAME見ると、これ以外にも<img>タグ等に書く設定などについて書かれていますが、 なんとこれだけでLazy Loadしてくれるようになります!

    Lazy Loadされているかの確認

    <img>タグに対して lazyLoad というクラスが自動で付与され、 読み込み中の場合は isLoading 、読み込みが終わると isLoaded というクラスが付与されるようになります。


    これで自動的にLazy Loadされるようになります。

    Lazy Loadしてくれている

    background imageに設定する

    lazy-background を使います

    <div lazy-background="~/assets/images/background-image.jpg">
      Content
    </div>

    指定の画像のみにLazy Loadを設定する

    特定の画像のみをLazy Loadしたい場合はまずnuxt.config.jsで directiveOnly: true を設定します

    nuxt.config.js
    export default {
      modules: [
        [
          'nuxt-lazy-load',
          {
            directiveOnly: true,
          },
        ],
      ]
      ・・・

    そしてLazy Loadさせたい <img> に対して v-lazy-load を指定します。

    <img data-src="image.png" alt="" title="" v-lazy-load />

    nuxt-lazy-loadの設定色々

    nuxt-lazy-loadはnuxt.config.jsに色々なオプションを設定をする事が出来ます。

    公式ページのREADMEをそのまま持ってくるとこのように書かれています。

    nuxt.config.js
    modules: [
      ['nuxt-lazy-load', {
        // These are the default values
        images: true,
        videos: true,
        audios: true,
        iframes: true,
        native: false,
        polyfill: true,
        directiveOnly: false,
     
        // Default image must be in the static folder
        defaultImage: '/images/default-image.jpg',
     
        // To remove class set value to false
        loadingClass: 'isLoading',
        loadedClass: 'isLoaded',
        appendClass: 'lazyLoad',
     
        observerConfig: {
          // See IntersectionObserver documentation
        }
      }]
    ]

    デフォルトで画像も設定出来るようですし、読み込み中のクラス名も変更出来たりと便利です!

    参考資料
    プロフィールの背景画像 プロフィール画像
    Yuki Takara
    都内でフリーランスのエンジニアをやってます。フロントとアプリ開発メインに幅広くやってます。