这两种异步加载图像的方式有何不同?

时间:2017-05-21 06:52:55

标签: javascript html

鉴于此HTML(数据URI只是一个空图像):

<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="/path/to/img.jpg" width="100" height="100">

这些方法的性能影响是什么?如果它们大部分是相同的,我应该使用选项A并避免在循环中声明一个函数吗?

选项A:

document.onload = function() {
    let images = document.querySelectorAll('img[data-src]');

    for (let i = 0, length = images.length; i < length; i++) {
        images[i].src = images[i].getAttribute('data-src');

        // And optionally
        images[i].removeAttribute('data-src');
    }
};

选项B:

document.onload = function() {
    let images = document.querySelectorAll('img[data-src]');

    for (let i = 0, length = images.length; i < length; i++) {
        let downloadingImage = new Image();

        downloadingImage.onload = function() {
            images[i].src = this.src;   
        };

        downloadingImage.src = images[i].getAttribute('data-src');

        // And optionally
        images[i].removeAttribute('data-src');
    }
};

0 个答案:

没有答案