鉴于此HTML(数据URI只是一个空图像):
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
data-src="/path/to/img.jpg" width="100" height="100">
这些方法的性能影响是什么?如果它们大部分是相同的,我应该使用选项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');
}
};
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');
}
};