[英]CSS/JS Lazy Loading Background Images (White Flicker)
所以我一直在嘗試延遲加載背景圖像,最初是低分辨率圖像,然后換成高分辨率圖像。 我嘗試了幾種不同的惰性加載器,但它們似乎都有相同的問題 - 當圖像交換時會出現閃爍。 我使用了 Yall Lazy Image Loader,並添加了一些修改,以便之前實際加載圖像,將其應用於背景圖像 - 但是圖像變化時仍有短暫的白色閃爍。 在 Firefox 中更為明顯,並且在未緩存圖像時發生。
有任何想法嗎? 這是一個代碼筆:
https://codepen.io/kehza/pen/PoPKZBa
newImg.onload = function () {
this.backgroundTarget.classList.remove(lazyBackgroundClass);
this.parentNode.removeChild(this);
};
提前致謝。
首先將兩個元素渲染到 DOM,然后再更改不透明度值應該是最高效的,因為瀏覽器不會再次繪制或合成圖層。 您可以利用新的"loading=lazy"
屬性,瀏覽器將為您完成這項工作。 下面的代碼可以調整為使用背景圖像而不是內聯圖像。 如果您仍然看到閃爍,請考慮.wrapper
上的will-change
屬性。
<div class="wrapper">
<img class="lowres" src="https://cdn.shopify.com/s/files/1/0254/2426/5278/files/Suited-Racer_200x.jpg" />
<img class="highres" loading="lazy" src="https://cdn.shopify.com/s/files/1/0254/2426/5278/files/Suited-Racer_1920x.jpg" />
</div>
js
document.querySelectorAll('img.highres').forEach(img => {
img.addEventListener('load', e => {
img.parentElement.classList.add('highres-loaded'))
})
})
css
.wrapper {
position: relative;
line-height: 0;
/* set fixed size for your page */
width: 100%;
height: 500px;
}
.wrapper img {
position: absolute;
display: inline-block;
width: 100%;
height: 100%;
}
.highres {
opacity: 0;
}
.highres-loaded .lowres {
opacity: 0;
}
.highres-loaded .highres {
opacity: 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.