封装一个图片懒加载方法在imagesPreLoader.js里:
export const preLoadImg = source => {
const pr = []
const images = []
source.forEach(url => {
let p = loadImage(url)
.then(img => images.push(img))
.catch(err => console.log(err))
pr.push(p)
})
return Promise.all(pr)
}
const loadImage = url => {
return new Promise((resolve, reject) => {
let img = new Image()
img.onload = () => resolve(img)
img.onerror = reject
img.src = url
})
}
在VUE中使用,在main.js里引用:
import { preLoadImg } from './utils/imagesPreLoader'
;(async () => {
await preLoadImg([require('./assets/images/bg.jpg'), require('./assets/images/bg-rules.png'), require('./assets/images/bg-prize.png')])
new Vue({
el: '#app',
components: { App },
template: '<App/>'
})
})()
网友评论