【问题标题】:How to wait for images loaded with javascript?如何等待用 javascript 加载的图像?
【发布时间】:2014-11-27 08:14:52
【问题描述】:

我有一个 div,我在其中附加了 imgs。使用 AJAX 加载 20 个项目的图像。他们用 jQuery 动画显示。动画延迟的问题。我认为有两个问题:

  1. 用于显示的图像未下载,我想现在显示它们
  2. 当我将 css display: block 设置为 img 时,浏览器绘制图像时出现延迟

那么问题是如何等待图片包(20个项目)被下载以及如何处理绘画延迟?

P/S。如果我为所有 img-tags 显示空 div(只需将它们设置为背景颜色)或 1 个图像,则动画效果很快。

【问题讨论】:

标签: javascript jquery html css image


【解决方案1】:

你可以使用这个sn-p。它不依赖于任何库,并且在我们的项目中运行良好。

/*
 * Preload an image if not cached, then call a callback function
 * @param {String} the image url
 * @param {Function} the callback function
*/
function loadImg(url, fn) {
    var img = new Image();
    img.src = url;
    if (img.complete) { // If the image has been cached, just call the callback
        if (fn) fn.call(img, true);
    } else {
        img.onerror = function() { // If fail to load the image
            if (fn) fn.call(img, false);
        };
        img.onload = function() { // If loaded successfully
            if (fn) fn.call(img, true);
            //On IE6, multiple frames in a image will fire the 'onload' event for multiple times. So set to null
            img.onload = null; 
        };
    };
}

对于您的场景,您可以传入一个回调函数,例如:

var callback = function(loaded) {
    if (loaded === true) {
        // do the animation. 
        var img = this; // now `this` points to the image itself.
    } else {
        // show default image or 'image failed to load'.
    }
}

【讨论】:

    【解决方案2】:

    您可以使用我的jQuery plugin 等待图片下载到您的新元素中。

    $('#container').waitForImages().done(function() { 
      $(this).addClass('ready');
    });
    

    【讨论】:

      【解决方案3】:

      使用.complete的javascript

      <img src="http://www.zastavki.com/pictures/originals/2013/Photoshop_Image_of_the_horse_053857_.jpg" id="something" />
      
      var myVar = setInterval(function(){
          console.log("loading")
          if( document.getElementById("something").complete ) { // checks if image is loaded
              console.log( "loaded" );
              clearInterval(myVar);
          }
      }, 500);
      

      here 是 jsfiddle 演示。

      【讨论】:

      【解决方案4】:

      您可以提前预加载图像(因此它们都已在缓存中准备就绪,并且在加载时不会有任何延迟),也可以在需要时加载它们并在开始动画之前在加载时使用通知.无论哪种方式,如果您想要一个流畅的运行动画,您需要确保在开始动画之前加载图像。

      您可以查看这些其他参考资料,了解如何使用代码示例预加载图像。第一个引用支持一个回调,当所有图像都加载完毕后会被调用:

      Image preloader javascript that supports events

      Is there a way to load images to user's cache asynchronously?

      How do you cache an image in Javascript

      【讨论】:

      • 如果没有代码示例,这个答案真的没用。
      • @Pavlo - 所有三个参考资料都是我以前关于该主题的代码示例的答案。我认为没有必要或不适合在此答案中重复代码 - 因此我包含参考链接。
      猜你喜欢
      • 2011-01-21
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      • 2015-01-24
      • 2017-07-19
      相关资源
      最近更新 更多