显示静态图像,但如果完全加载则与动画 GIF 交换一次 GIF

Show static image but swap with animated GIF once GIF if fully loaded

我正在构建一个包含许多大型 (800KB) 动画 GIF 的网站。我还有我计划最初显示的每个 GIF 的第一帧,然后在它们加载后将其交换到动画 GIF。这样网站最初看起来仍然很好。

我目前将 GIF url 作为 "data-gif='blah.gif'" 存储在图像标签中。然后我可以使用 jQuery 遍历这些以获取 GIF URL。

现在我不确定如何在后台加载它们并在加载它们时获取事件。

你想要一个 "image preloader"。这是一个帮助您入门的示例,但我建议您搜索一个在处理边缘情况方面有更多想法的库。

function preload(i, img) {
  console.log(img);
  var $img, url, $pre;
  
  $img = $(img);
  
  // incoming <img/> must have a 'data-gif' attribute
  if (! $img || ! $img.data('gif')) {
    return;
  }

  url = $img.data('gif');
  $pre = $('<img />');

  // Set up handler to replace original images's 'src' attribute
  // with the data-gif URL once the replacement is loaded
  $pre.on('load', function() {
    $img.attr('src', url);
  });

  $pre.attr('src', url);
}

$('#images img').each(preload);
#images img {
  width: 320px;
}

#images {
  list-style: none;
}

#images li {
  margin-bottom: 2rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>Image preloader test</h1>
<ul id="images">
<li><img src="//placehold.it/960x540/99eeee" data-gif="http://static1.1.sqspcdn.com/static/f/1376538/22414391/1365600694390/typing.gif?token=v5utJCt1OsYJZ%2BIzFfWubDICtZI%3D" /></li>

  <li><img src="//placehold.it/960x540/ee99ee" data-gif="http://static1.1.sqspcdn.com/static/f/1376538/22414389/1365600692520/reading.gif?token=v5utJCt1OsYJZ%2BIzFfWubDICtZI%3D" /></li>

  <li><img src="//placehold.it/960x540/eeee99" data-gif="http://static1.1.sqspcdn.com/static/f/1376538/22414392/1365600694820/wireframe.gif?token=v5utJCt1OsYJZ%2BIzFfWubDICtZI%3D" /></li>

  <li>Broken link: never swaps:<br/><img src="//placehold.it/960x540/999999" data-gif="http://example.com/asfazsdasfd.gif" /></li>

</ul>