LoginSignup
6
3

More than 1 year has passed since last update.

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

Last updated at Posted at 2019-08-04

手順

  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

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