My Vue CLI app contains a feature where a series of images transition when a user clicks a button. The issue arises when the image loading is delayed until the button click, causing a choppy experience as the images suddenly pop in during the transition, disrupting other elements. To enhance user experience, I aim to preload the images upon site loading.
The solution proposed in this answer involves utilizing the Image
class. However, considering the Vue CLI documentation, Vue employs its own plugin - preload-webpack-plugin, which has the potential to be configured based on requirements.
My attempt at configuration to preload images:
vue.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const PreloadWebpackPlugin = require('@vue/preload-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new HtmlWebpackPlugin(),
new PreloadWebpackPlugin({
rel: 'prefetch',
as (entry) {
if (/\.css$/.test(entry)) return 'style';
if (/\.woff$/.test(entry)) return 'font';
if (/\.png$/.test(entry)) return 'image';
return 'script';
}
})
]
}
}
Unfortunately, this configuration disrupts the final index.html
, resulting in missing build scripts and styles.
Stripping out the line:
new HtmlWebpackPlugin(),
The site still functions, but image prefetching does not occur. It's as if the vue.config.js
changes were insignificant.
How can I properly set this up?
Edit: Within Vue components, image loading is achieved using require()
, thus passing through Webpack. For instance:
<img :src="require('../assets/img/' + img)" draggable="false">
Edit: I managed to prefetch images following Roy J's suggestion in the comments:
PreloadImages.vue
within my main component:
<template>
<div style="display: none;">
<img :src="require('../assets/img/foo.png')">
<img :src="require('../assets/img/bar.png')">
<img :src="require('../assets/img/baz.png')">
</div>
</template>
However, although this prefetches images, it does not involve resource hints through <link>
tags and may not be the best practice due to additional effort involved.