HTML做懒加载需要的兼容问题,前端性能优化--懒加载和预加载

懒加载

代码实现

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)

效果

蓝色为已经请求加载的图片

红色为还没有请求加载的图片

默认打开,没有操作前

bVboQlb?w=2065&h=907

向下滚动前

bVboQlL?w=1473&h=795

向下滚动后

bVboQlI?w=1509&h=831

冷门属性

ocument.addEventListener(事件监听)

document.addEventListener('scroll', function() {

console.log('aa')

})

bVboQpB?w=1232&h=788

dataset

用`dataset.original`获取`data-original` 的属性

img.onload

事件在图片加载完成后立即执行

getBoundingClientRect

用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性

文档各种高度

document.documentElement.clientHeight:视口的大小

document.documentElement.scrollHeight:文档的大小

document.documentElement.offsetHeight:文档的大小

bVboQnT?w=1058&h=796

预加载

标签

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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值