图像加载时的 jQuery 回调(即使图像被缓存)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3877027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:15:59  来源:igfitidea点击:

jQuery callback on image load (even when the image is cached)

jqueryimagejquery-eventsjquery-load

提问by Tom Lehman

I want to do:

我想要做:

$("img").bind('load', function() {
  // do stuff
});

But the load event doesn't fire when the image is loaded from cache. The jQuery docssuggest a pluginto fix this, but it doesn't work

但是从缓存加载图像时不会触发 load 事件。jQuery 文档建议使用插件来解决此问题,但它不起作用

回答by Nick Craver

If the srcis already set, then the event is firing in the cached case, before you even get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete, like this:

如果src已经设置,则事件在缓存的情况下触发,甚至在您绑定事件处理程序之前。要解决此问题,您可以循环检查和触发基于 off 的事件.complete,如下所示:

$("img").one("load", function() {
  // do stuff
}).each(function() {
  if(this.complete) {
      $(this).load(); // For jQuery < 3.0 
      // $(this).trigger('load'); // For jQuery >= 3.0 
  }
});

Note the change from .bind()to .one()so the event handler doesn't run twice.

请注意从.bind()to的更改,.one()以便事件处理程序不会运行两次。

回答by Gus

Can I suggest that you reload it into a non-DOM image object? If it's cached, this will take no time at all, and the onload will still fire. If it isn't cached, it will fire the onload when the image is loaded, which should be the same time as the DOM version of the image finishes loading.

我可以建议您将其重新加载到非 DOM 图像对象中吗?如果它被缓存,这根本不需要时间,并且 onload 仍然会触发。如果它没有被缓存,它会在加载图像时触发 onload,这应该与图像的 DOM 版本完成加载的时间相同。

Javascript:

Javascript:

$(document).ready(function() {
    var tmpImg = new Image() ;
    tmpImg.src = $('#img').attr('src') ;
    tmpImg.onload = function() {
        // Run onload code.
    } ;
}) ;

Updated (to handle multiple images and with correctly ordered onload attachment):

更新(以处理多个图像和正确排序的加载附件):

$(document).ready(function() {
    var imageLoaded = function() {
        // Run onload code.
    }
    $('#img').each(function() {
        var tmpImg = new Image() ;
        tmpImg.onload = imageLoaded ;
        tmpImg.src = $(this).attr('src') ;
    }) ;
}) ;

回答by guari

My simple solution, it doesn't need any external plugin and for common cases should be enough:

我的简单解决方案,它不需要任何外部插件,对于常见情况应该足够了:

/**
 * Trigger a callback when the selected images are loaded:
 * @param {String} selector
 * @param {Function} callback
  */
var onImgLoad = function(selector, callback){
    $(selector).each(function(){
        if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
            callback.apply(this);
        }
        else {
            $(this).on('load', function(){
                callback.apply(this);
            });
        }
    });
};

use it like this:

像这样使用它:

onImgLoad('img', function(){
    // do stuff
});

for example, to fade in your images on load you can do:

例如,要在加载时淡入图像,您可以执行以下操作:

$('img').hide();
onImgLoad('img', function(){
    $(this).fadeIn(700);
});


Or as alternative, if you prefer a jquery plugin-like approach:

或者作为替代,如果您更喜欢类似 jquery 插件的方法:

/**
 * Trigger a callback when 'this' image is loaded:
 * @param {Function} callback
 */
(function($){
    $.fn.imgLoad = function(callback) {
        return this.each(function() {
            if (callback) {
                if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
                    callback.apply(this);
                }
                else {
                    $(this).on('load', function(){
                        callback.apply(this);
                    });
                }
            }
        });
    };
})(jQuery);

and use it in this way:

并以这种方式使用它:

$('img').imgLoad(function(){
    // do stuff
});

for example:

例如:

$('img').hide().imgLoad(function(){
    $(this).fadeIn(700);
});

回答by Bj?rn

Do you really have to do it with jQuery? You can attach the onloadevent directly to your image as well;

你真的必须用jQuery来做吗?您也可以将onload事件直接附加到您的图像上;

<img src="/path/to/image.jpg" onload="doStuff(this);" />

It will fire every time the image has loaded, from cache or not.

无论是否从缓存加载图像,它都会触发。

回答by Piotr St?pniewski

You can also use this code with support for loading error:

您还可以使用此代码支持加载错误:

$("img").on('load', function() {
  // do stuff on success
})
.on('error', function() {
  // do stuff on smth wrong (error 404, etc.)
})
.each(function() {
    if(this.complete) {
      $(this).load();
    } else if(this.error) {
      $(this).error();
    }
});

回答by Sammaye

I just had this problem myself, searched everywhere for a solution that didn't involve killing my cache or downloading a plugin.

我自己也遇到了这个问题,到处搜索不涉及杀死我的缓存或下载插件的解决方案。

I didn't see this thread immediately so I found something else instead which is an interesting fix and (I think) worthy of posting here:

我没有立即看到这个帖子,所以我找到了其他的东西,这是一个有趣的修复并且(我认为)值得在这里发布:

$('.image').load(function(){
    // stuff
}).attr('src', 'new_src');

I actually got this idea from the comments here: http://www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/

我实际上从这里的评论中得到了这个想法:http: //www.witheringtree.com/2009/05/image-load-event-binding-with-ie-using-jquery/

I have no idea why it works but I have tested this on IE7 and where it broke before it now works.

我不知道它为什么起作用,但我已经在 IE7 上测试过它,并且在它现在起作用之前它在哪里坏了。

Hope it helps,

希望能帮助到你,

Edit

编辑

The accepted answer actually explains why:

接受的答案实际上解释了原因:

If the src is already set then the event is firing in the cache cased before you get the event handler bound.

如果 src 已经设置,那么在绑定事件处理程序之前,事件会在缓存中触发。

回答by nick

By using jQuery to generate a new image with the image's src, and assigning the load method directly to that, the load method is successfully called when jQuery finishes generating the new image. This is working for me in IE 8, 9 and 10

通过使用jQuery用图像的src生成一个新图像,并直接为其分配load方法,当jQuery完成生成新图像时成功调用load方法。这在 IE 8、9 和 10 中对我有用

$('<img />', {
    "src": $("#img").attr("src")
}).load(function(){
    // Do something
});

回答by AllisonC

A solution I found https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12(This code taken directly from the comment)

我找到了一个解决方案https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12(此代码直接取自评论)

var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;

回答by Chuck Conway

A modification to GUS's example:

对 GUS 示例的修改:

$(document).ready(function() {
    var tmpImg = new Image() ;
    tmpImg.onload = function() {
        // Run onload code.
    } ;

tmpImg.src = $('#img').attr('src');
})

Set the source before and after the onload.

在加载之前和之后设置源。

回答by Bj?rn T. Dahl

Just re-add the src argument on a separate line after the img oject is defined. This will trick IE into triggering the lad-event. It is ugly, but it is the simplest workaround I've found so far.

只需在定义 img 对象后在单独的行上重新添加 src 参数。这将诱使 IE 触发 lad-event。这很丑陋,但这是我迄今为止找到的最简单的解决方法。

jQuery('<img/>', {
    src: url,
    id: 'whatever'
})
.load(function() {
})
.appendTo('#someelement');
$('#whatever').attr('src', url); // trigger .load on IE