最近公司要做年终总结需求, 涉及大量图片, 做过活动的小伙伴都知道应该, 涉及大量图片需求都要做图片预加载.所谓图片预加载就是在项目初始化时先将图片缓存到本地, 然后项目直接读取缓存图片,如果不做预加载的话, 图片很受网速影响, 刚进页面图片总是显示空白, 如果页面有用到大量动画,用户体验将会很差.
看了一下网上的方案,一般都是用一个数组存储所有用到的图片文件名, 然后项目初始化时通过图片 new image() 来缓存图片, 实现的原理基本都是一致的,但是上面的方式在开发上不是很好, 比如说,我每次修改图片,是不是都要更新存储图片的数组.今天我们要说的就是通过脚本的形式来完成上述操作:
写脚本之前我们有以下一点需要说明:
- 静态资源必须放在public 文件夹下, 原因是public资源不会经过 webpack处理, 如果放在 src 下的 assets文件, 经过 webpack 处理, 资源就读取不到了。
脚本如下:
const path = require('path')
const reg = /.(png|jpe?g|gif)$/
const prentPath = './public'
const imgPath = './public/img'
const fs = require('fs')
const readImg = (rootPath) => {
const imgArr = [];
// eslint-disable-next-line no-shadow
const readImg = (path) => {
const files = fs.readdirSync(path);
files.forEach((file) => {
if (fs.statSync(`${path}/${file}`).isFile() && reg.test(file)) {
imgArr.push(file);
} else if (fs.statSync(`${path}/${file}`).isDirectory()) {
readImg(`${path}/${file}`);
}
});
};
readImg(rootPath);
return imgArr;
};
const runImgGo = () => {
try {
const imgArr = readImg(path.resolve(__dirname, imgPath));
const buf = `window._$_imgArr_ = ${JSON.stringify(imgArr)};`;
const fd = path.resolve(__dirname, `${prentPath}/imgArr.js`);
fs.writeFile(fd, buf, (err) => {
console.log('图片写入完成');
if (err) {
throw err;
}
});
} catch (error) {
console.log(error, '图片写入失败');
setTimeout(() => {
runImgGo()
}, 1000)
}
};
runImgGo()
上面的脚本执行完会在根目录生成一个 imgArr.js 文件, 这个文件就是通过 node 脚本生成的存储静态资源的文件, 它会将 public 下的 img 文件夹中所有图片的文件名提取出来,放在一个 Array 中. 这样我们就将上面通过手动管理静态资源的方式改成了通过脚本的形式管理了. 最后我们只需在 index.html文件中通过 script 标签引入这个文件就可以了.是不是感觉优雅了很多呢









网友评论