|
|
以下是对代码进行的一些优化建议:
1. 使用Passive Event Listeners (PEL)来改进scroll事件的性能,避免滑动时出现卡顿。可以将第一个addEventListener中的选项改为{passive: true}。
2. 将isInViewPort函数中的viewWidth和viewHeight提取到函数外部,在函数之外只需计算一次即可,减少计算次数。
3. 将lazyloadThrottleTimeout变量的初始值设置为null,而不是undefined。
4. 将setTimeout的延迟时间从20毫秒调整为50毫秒,降低了计算频率,以优化代码的性能。
5. 将forEach中的回调函数改写成普通的for循环,这可以在某些浏览器中提高循环的速度。
根据以上优化建议,代码可重新编写为:
```
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages = document.querySelectorAll(".img.lazy");
var lazyloadThrottleTimeout = null;
var viewWidth = window.innerWidth || document.documentElement.clientWidth;
var viewHeight = window.innerHeight || document.documentElement.clientHeight;
function lazyload() {
if (lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function() {
for (var i = 0; i < lazyloadImages.length; i++) {
if (isInViewPort(lazyloadImages[i])) {
lazyloadImages[i].classList.remove('lazy');
}
}
if (lazyloadImages.length == 0) {
document.removeEventListener("scroll", lazyload, {passive: true});
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 50);
}
function isInViewPort(element) {
const {
top,
right,
bottom,
left,
} = element.getBoundingClientRect();
return (
top >= 0 &&
top <= viewHeight &&
left >= 0
);
}
document.addEventListener("scroll", lazyload, {passive: true});
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
});
``` |
|