Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have some pretty basic jQuery code:

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

However, thats not firing consistently. It fires if i do a hard refresh or close my browser, but a normal refresh, or just hitting the same URL twice at any time without erasing the cache makes the .load() never fire.

Any ideas on how to fix this?

like image 791
Oscar Godson Avatar asked Apr 11 '11 16:04

Oscar Godson


3 Answers

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){
    …
});
like image 122
Raphael Schweikert Avatar answered Nov 20 '22 15:11

Raphael Schweikert


A way would be to add a "dummy variable" at the end of the URL that you use to grab the image... such as the time in milliseconds appended as a query string param.

Edit: Preventing the Browser to Cache images is a very bad idea in 99% of the cases as it will slow down your application. Instead you should check if an image is already loaded, and if not wait for the load event to complete.

like image 4
El Guapo Avatar answered Nov 20 '22 16:11

El Guapo


As Ron and El Guapo said, the answer is to add a query at the end of the URL. I did this like this:

$(this).find('img').each(function(){
   $(this).attr('src',$(this).attr('src')+'?'+new Date().getTime())  
}).load(function(){
   //This will always run now!
like image 3
Oscar Godson Avatar answered Nov 20 '22 17:11

Oscar Godson