0

我面临一个问题,似乎无法找到解决方案。我有一个部分标签

<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可以加载,一旦加载,替换静态图像。

我已经看到使用图像对象的示例,例如在页面加载后动态替换图像 src 并且图像完全下载

但是,我找不到任何可以使用背景图像执行此操作的内容。

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

谢谢

4

2 回答 2

1

通过提供section.background-gif占位符图像(在您的情况下,它可以是GIF您要加载的图像的缩小图像),并给它一个data-src包含所需GIF图像的路径/链接的属性,然后使用JavaScript我们将加载GIF基于图像在元素的data-src属性上section.background-gif,当它加载时,我们会将其src属性分配给元素的background-image属性section.background-gif

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

在该片段中,我使用了来自 placeholder.com 网站的占位符图片,该图片最初显示为背景,然后我GIF从 Google 加载了一张随机图片。由于某些限制,该代码段可能无法按预期工作(因为代码段是沙盒化的),因此请在您的项目中尝试它应该可以工作,只是不要忘记用您的替换图像链接。

// 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>

希望我把你推得更远。

于 2018-09-10T23:17:12.613 回答
-1

您可以尝试预加载图像。将图像作为对象预加载将允许链接事件侦听器,包括“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';
});
}

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

于 2018-09-10T22:33:31.737 回答