如何为用户加载大型动画 gif

How to load a large animated gif for the user

本文关键字:大型 动画 gif 加载 用户      更新时间:2023-09-26

我的网站将有一个大的动画gif(1900px宽)。如您所料,初始加载非常长,动画非常不稳定。有没有更好的方法来加载 gif,这样它就不会拖累网站(并使滚动断断续续)?

如果以

1px宽和1px高加载图像,则不会影响滚动。 这里有一个不错的小CSS/HTML大图像加载技巧:

<img src="http://placekitten.com/1000/1000" width="1" height="1" onload="this.style.height = 'auto'; this.style.width = 'auto';">

以 1px 大小加载图像,然后在加载时正常显示。

如果您只想在加载正文后加载图像,请尝试以下操作:

function initBanner(){
  
  var bannerSrc = "http://placekitten.com/1000/1000";
  // contains the src of the image
  
  var banner = document.getElementById('banner1');
  // this is the emage object
  
  banner.src = bannerSrc;
  // add the src to the image
  
  }
<body onload="initBanner()">
  <!-- when the body has finished loading, call function initBanner() -->
  <img id="banner1" src="" />
</body>

您可以预加载图像,然后在加载后将其插入页面中的某个位置:

var image = new Image();
image.onload = function() {
    document.body.appendChild(image);
};
image.src = 'image.gif';

JSFiddle