懒加载
代码实现
html
Document
css
.image-item {
display: inline-block;
width: 100%;
height: 300px;
background: gray;
}
js
var viewHeight = document.documentElement.clientHeight;
function lazyload() {
var imgs = document.querySelectorAll('img[data-original][lazyload]');
imgs.forEach(item => {
if (item.dataset.original == '') {
return;
}
var rect = item.getBoundingClientRect();
if (rect.bottom >= 0 && rect.top < viewHeight) {
var img = new Image();
img.src = item.dataset.original;
console.log(img.src)
img.onload = function() {
item.src = img.src;
}
item.removeAttribute('data-original');
item.removeAttribute('lazyload')
}
})
}
lazyload();
document.addEventListener('scroll', lazyload)
效果
蓝色为已经请求加载的图片
红色为还没有请求加载的图片
默认打开,没有操作前
向下滚动前
向下滚动后
冷门属性
ocument.addEventListener(事件监听)
document.addEventListener('scroll', function() {
console.log('aa')
})
dataset
用`dataset.original`获取`data-original` 的属性
img.onload
事件在图片加载完成后立即执行
getBoundingClientRect
用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性
文档各种高度
document.documentElement.clientHeight:视口的大小
document.documentElement.scrollHeight:文档的大小
document.documentElement.offsetHeight:文档的大小
预加载
标签
new Image()
var image = new Image();
image.src = 'https://img.alicdn.com/imgextra/i4/2260152888/O1CN01vw2e251XCkJr0VPZU_!!2260152888-0-beehive-scenes.jpg_250x250xz.jpg';
xml
var queue = new createjs.LoadQueue();
queue.installPlugin(createjs.Sound);
queue.on("complete", handleComplete, this);
queue.loadFile({
id: "sound",
src: "http://path/to/sound.mp3"
});
queue.loadManifest([{
id: "myImage",
src: "path/to/myImage.jpg"
}]);
function handleComplete() {
createjs.Sound.play("sound");
var image = queue.getResult("myImage");
document.body.appendChild(image);
}