美文网首页JavaScriptVue
Vue中引入ES6 图片预加载

Vue中引入ES6 图片预加载

作者: Lia代码猪崽 | 来源:发表于2018-11-07 15:36 被阅读2次

    封装一个图片懒加载方法在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/>'
        })
    })()
    

    相关文章

      网友评论

        本文标题:Vue中引入ES6 图片预加载

        本文链接:https://www.haomeiwen.com/subject/wilvxqtx.html