jQuery .load() not firing on images (probably caching?)

后端 未结 3 1978
醉酒成梦
醉酒成梦 2020-12-14 10:11

I have some pretty basic jQuery code:

...
$(this).find(\'img\').load(function(){
   loadedImages++;
   if(loadedImages == $this.find(\'img\').length){
...
         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 10:45

    I think this has been discussed before. It’s not the caching per se that is the problem but the timing: the images may already have been loaded by the time the event handler is attached (so it never gets fired). This may also occur if no caching happens, for example in a multithreaded browser on a very fast connection. Fortunately, there is a property .complete that you can use:

    var load_handler = function() {
        loadedImages++;
        …
    }
    $(this).find('img').filter(function() {
        return this.complete;
    }).each(load_handler).end().load(load_handler);
    

    You can also create your own event attach function:

    jQuery.fn.extend({
        ensureLoad: function(handler) {
            return this.each(function() {
                if(this.complete) {
                    handler.call(this);
                } else {
                    $(this).load(handler);
                }
            });
        }
    });
    

    And then call it as follows:

    $(this).find('img').ensureLoad(function(){
        loadedImages++;
        if(loadedImages == $this.find('img').length){
        …
    });
    

提交回复
热议问题