懒加载
将img标签中设置一个data-src属性,它指向的是实际上我们需要加载的图像,而img的src指向一张默认的图片,如果为空的话也会向服务器发送请求。当用户访问可视区域的img元素时,将src得值替换为data-src指向的实际资源加载的图像。
- 优点
- 用户可以更快地加载到内容,因为用户第一次打开网站时只需要加载一部分内容。
- 较低的资源成本,因为内容只在用户需要时才加载,而不是一次完成。
- IntersectionObserver实现
一种可以异步监听目标元素与其祖先或视窗(viewport)是否处于交叉状态的方式。
// 加载img
function preloadImage(img) {
const src = img.dataset.src;
if (!src) {
return;
}
img.src = src;
}
const config = {
rootMargin: '0px',
threshold: 0
};
const observer = new IntersectionObserver((entries, self) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 加载图像
preloadImage(entry.target);
// 解除观察
self.unobserve(entry.target);
}
})
}, config);
// 监听所有img元素
const images = document.querySelectorAll('[data-src]');
images.forEach(image => {
observer.observe(image);
});
预加载
将所有所需的资源提前请求加载到本地,这样后面在需要用到时就直接从缓存取资源。
- 优点
- 减少用户等待时间,提升体验。
- 使用HTML标签
<img src="http://pic26.nipic.com/20121213/61681830044449030002.jpg" style="display:none" />
- 使用Image对象
var image= new Image();
image.src = "http://pic26.nipic.com/20121213/61681830044449030002.jpg";
- 使用ajax请求图片资源