I have an app with the Vue CLI. When the app loads, I have a bunch of images that appear with a transition when a user clicks a button. The problem is that when the user clicks a button, the corresponding image only then starts to load, meaning that most of the animation is done until then. This makes the experience quite choppy because the images suddenly pop in during the transition, displacing other elements. I want to prefetch them when the site loads.
This answer suggests using the Image
class. However, according to the Vue CLI docs, Vue internally uses its own plugin for that, preload-webpack-plugin, and it apparently can be configured.
I tried to configure it so that it preloads 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';
}
})
]
}
}
This only manages to screw up the final index.html
, leaving it without the build scripts and styles inside.
If I remove this line:
new HtmlWebpackPlugin(),
The site still loads but the images are not prefetched. It's the same as if I never did anything in the vue.config.js
file.
How do I set it up correctly?
Edit: In Vue components, I use require()
to load the images, meaning they pass through Webpack. For example:
<img :src="require('../assets/img/' + img)" draggable="false">
Edit: I was able to prefetch the images as Roy J suggested in the comments:
PreloadImages.vue
in 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, that's not the answer to my actual question - it doesn't use resource hints via <link>
tags. It also requires more effort and I believe it's a bad practice.