var index = 1;
// 初始化部分图片
imgLoad();
// 滑动事件
window.onscroll = function load(){
imgLoad();
}
// 懒加载图片
function imgLoad(){
var img = document.getElementById('img'+index);
var offsetTop = document.body.scrollTop || document.documentElement.scrollTop;
while((img.offsetTop - offsetTop) < window.innerHeight && index < 10){ //这里index用于测试, 加载图片张数为10张
index++;
// 创建新div
var div = document.createElement("div");
div.style.cssText = "background:url('./img" +index + ".png') no-repeat";
img.parentNode.insertBefore(div,img.nextSibling)
// 赋予id
div.id = "img"+index;
img = document.getElementById('img'+index);
}
}
本文介绍了一种网页中常见的懒加载技术实现方式。通过监听页面滚动事件并动态插入背景图片,可以有效减少页面初始加载时间,提高用户体验。文中给出了具体的JavaScript代码示例。
187

被折叠的 条评论
为什么被折叠?



