简体   繁体   English

CSS/JS 延迟加载背景图片(白色闪烁)

[英]CSS/JS Lazy Loading Background Images (White Flicker)

So I've been trying to lazy load background images, by initially having a low res image which then gets swapped out to a high res one.所以我一直在尝试延迟加载背景图像,最初是低分辨率图像,然后换成高分辨率图像。 I've tried a few different lazy loaders, but they all seem to have the same issue - when the image swaps there is a flicker.我尝试了几种不同的惰性加载器,但它们似乎都有相同的问题 - 当图像交换时会出现闪烁。 I've used Yall Lazy Image Loader, and added some modifications so that the image is actually loaded before, being applied to the background image - however there is still a brief white flicker of the image changing.我使用了 Yall Lazy Image Loader,并添加了一些修改,以便之前实际加载图像,将其应用于背景图像 - 但是图像变化时仍有短暂的白色闪烁。 It's more noticeable in Firefox, and happens when the image isn't cached.在 Firefox 中更为明显,并且在未缓存图像时发生。

Any ideas?有任何想法吗? Here's a codepen:这是一个代码笔:

https://codepen.io/kehza/pen/PoPKZBa https://codepen.io/kehza/pen/PoPKZBa

newImg.onload = function () {
    this.backgroundTarget.classList.remove(lazyBackgroundClass);
    this.parentNode.removeChild(this);
};

Thanks in Advance.提前致谢。

Rendering both elements to the DOM first and later changing the opacity values should be the most performant because the browser will not paint or composite the layers again.首先将两个元素渲染到 DOM,然后再更改不透明度值应该是最高效的,因为浏览器不会再次绘制或合成图层。 You can leverage the new "loading=lazy" attribute and the browser will do that work for you.您可以利用新的"loading=lazy"属性,浏览器将为您完成这项工作。 The code below can be tweaked to use background images instead of inline images.下面的代码可以调整为使用背景图像而不是内联图像。 Consider the will-change attribute on .wrapper if you still seeing flickering.如果您仍然看到闪烁,请考虑.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 js

document.querySelectorAll('img.highres').forEach(img => {
  img.addEventListener('load', e => {
    img.parentElement.classList.add('highres-loaded'))
  })
})

css 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM