是否需要图片懒加载? 并且一个简单的图片懒加载方案.

林三心 - 前端展示图片,到底该不该用 img 标签

new Image() 预加载

1
2
3
4
5
6
7
8
const img = new Image();
img.src = 'preload.png';

// 预防缓存可以增加时间戳
img.src = 'preload.png' + '?' + Date.now();
img.onload = function () {
...
}

实现带优先级的队列加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

class Preloader {
private activeCount = 0;
constructor(maxParalled = 3) {
this.queue = [];
this.maxParalled = maxParalled;
}

add(url) {
this.queue.push(url);
this.loadNext();
}

loadNext() {
while (this.activeCount < this.maxParalled && this.queue.length) {
const url = this.queue.shift();
this.activeCount++;

const img = new Image();
img.src = url;
this.onload = img.onerror = () => {
this.activeCount--;
this.loadNext();
}
}
}
}


// demo
const preloader = new Proloader();
preloader.add('test.png');

一言蔽之

img 标签的loading属性可以设置成lazy
即懒加载