手順
- nuxt.config.jsに追記
- webpをimport(webpは作成済みとする)
- data()でwebpをリターン
- webpを使用可能かを判定するmethodsを追記
- 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">
https://unpkg.com/vue-lazyload/vue-lazyload.js headerのscriptに追記します2<-リンク3<-スクショ 先ほどの記述を変更しますwebp+lazyload
cdnを使ってwebp+lazyloadを実現できます(多分nodemoduleでもできる){
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