加载后用 GIF 替换背景图像

Replace background image with GIF once loaded

我遇到了一些问题,似乎找不到解决方案。我有一个部分标签

<section class="background-gif"></section>

这只是加载背景图片

.background-gif {
    background: url(../images/image.gif) no-repeat top;
    background-size: 100%;
}

够直截了当。问题是,正在加载的 gif 是 5MB,因为它有很多动画。这导致页面加载速度非常慢。我不能使用标准的预加载器来满足要求。

相反,我想我会试一试这样的东西https://medium.com/front-end-hacking/how-to-optimize-image-loading-on-your-website-855020fb41ae

不过我的IDE好像不太喜欢这段代码,我觉得是ES6?所以我本质上是在尝试做类似的事情。我的想法是替换上面的 CSS 以便它最初显示静态图像。然后在后台加载gif,加载完成后替换静态图片。

我见过使用图像对象的例子,像这样

但是我找不到任何可以对背景图像执行此操作的东西。

主 gif 完全加载后,我将如何替换静态背景?

谢谢

您可以尝试预加载图片。将图像预加载为对象将允许链接事件侦听器,包括 "onload"。让我们试试这个....

window.addEventListener('load',init);

function init(){
var image = new Image();
image.src = 'https://images.unsplash.com/photo-1530482817083-29ae4b92ff15?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=44f4aebbd1e1371d5bf7dc22016c5d29&auto=format&fit=crop&w=700&q=60';

image.addEventListener('load',function(){
alert('image loaded');
document.body.style.background = 'url('+image.src+') no-repeat top';
});
}

让我知道如何使用更大的图像。我很好奇。

通过给 section.background-gif 一个占位符图像(在你的情况下,它可以是你想要加载的 GIF 图像的缩小图像),并给它一个 data-src包含所需 GIF 图像的 path/link 的属性,然后使用 JavaScript 我们将根据 [=13] 的 data-src 属性加载 GIF 图像=] 元素,当它加载时,我们会将其 src 属性分配给 section.background-gif 元素的 background-image 属性。

这里有一个可运行的片段来说明:

In the snippet, I'm using a placeholder image from placeholder.com website that initially appears as the background, then I load a random GIF image from Google. The snippet may not work as expected due to some restrictions(as the snippets are sandboxed), so try it in your project it should work, just don't forget to replace the image links with yours.

// referencing the section element, and creating a new Image object.
var section = document.getElementsByClassName('background-gif')[0],
    img = new Image();
// assign the data-src to the img variable src.
img.src = section.getAttribute('data-src');
// adding a 'load' event listener in which will change the section's background image when the img is loaded.
img.addEventListener('load', function() {
  // the img is loaded, assign its src attribute to the section.
  section.style.backgroundImage = 'url("' + this.src + '"';
  // just for testing, not required.
  console.log('The image has been loaded.');
});
section {
  /* just for the demo */
  height: 100vh;
}
.background-gif {
  /* change the url to your image link */
  background: url("https://via.placeholder.com/350x350") no-repeat top;
  background-size: 100%;
}
<!-- don't forget the data-src to point to the large GIF image you want to set as a background -->
<section class="background-gif" data-src="http://cosmicweb.uchicago.edu/images/mov/s02_0.gif"></section>

希望我能把你推得更远。