【问题标题】:Show static image but swap with animated GIF once GIF if fully loaded显示静态图像,但如果完全加载,则与动画 GIF 交换一次 GIF
【发布时间】:2016-02-02 11:10:08
【问题描述】:

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

我目前将图像标签中的 GIF 网址存储为“data-gif='blah.gif'”。然后我可以用 jQuery 遍历这些来获取 GIF URL。

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

【问题讨论】:

标签: javascript jquery image animated-gif


【解决方案1】:

您想要一个“图像预加载器”。这是一个帮助您入门的示例,但我建议您搜索一个对处理边缘情况有更多想法的库。

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>

【讨论】:

    猜你喜欢
    • 2011-02-09
    • 2011-05-28
    • 2017-11-10
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多