Help us understand the problem. What is going on with this article?

webpの読み込み判定 nuxt vue-lazyload

手順

  1. nuxt.config.jsに追記
  2. webpをimport(webpは作成済みとする)
  3. data()でwebpをリターン
  4. webpを使用可能かを判定するmethodsを追記
  5. webpを使いたいところに追記

nuxt.config.jsに追記します

nuxt.config.js
build: {
    extend(config, {
      isClient
    }) {
      config
        .module
        .rules
        .push({
          test: /\.(webp)$/i,
          loaders: [
            'file-loader?hash=sha512&digest=hex&name=[hash].[ext]'
          ]
        })   
     }
  },

webpをimportします

import imgwebp from '../static/images/lp/elem/abtest/image.webp'
import imgpng from '../static/images/lp/elem/abtest/image.png'

dataでreturnします

data () { 
  return {
    imgwebp: imgwebp,
    imgpng: imgpng
  }
}

methodにwebpを使えるか判定するメソッドを追記します 1

async canUseWebP () {
  if (process.browser) {// because require window variable
      var elem = await window.document.createElement('canvas')
    if (elem.getContext && (await elem.getContext('2d'))) {
        // was able or not to get WebP representation
      return (
          (await elem.toDataURL('image/webp').indexOf('data:image/webp')) ===
        0
      )
    }
    // very old browser like IE 8, canvas not supported
    return false
  }
}

使いたいところに記載します

<img
  :src="canUseWebP() ? imgwebp : imgpng"
/>
// OR
<img v-if="canUseWebP()" src="../static/images/lp/elem/abtest/image.webp">
<img v-else src="../static/images/lp/elem/abtest/image.png">

webp+lazyload

https://unpkg.com/vue-lazyload/vue-lazyload.js
cdnを使ってwebp+lazyloadを実現できます(多分nodemoduleでもできる)

headerのscriptに追記します2<-リンク3<-スクショ

{
  src: "/js/vue-lazyload.js"
}

先ほどの記述を変更します

<img
  v-lazy="this.canUseWebP() ? imgwebp : imgpng" // :srcをv-lazyに変更
/>

原因?

https://github.com/vuejs/vue-loader/pull/953
https://github.com/vuejs-templates/webpack/issues/396

以下参考

.webpを作るには4 | 5

webpを/staticに配置します6 | 7

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away