3

In the jQuery docs for the load event http://api.jquery.com/load-event/, it says Can cease to fire for images that already live in the browser's cache. Is any more information available on this, such as what browsers it affects, and in what situations?

Cameron Martin
  • 5,764
  • 1
  • 35
  • 52

1 Answers1

10

I'm not sure what browsers are affected, but it is easy to check for.

var img = new Image();
img.src = "foo.jpg";
if (img.complete || img.readyState === 4) {
    // image is cached
    doneCallback();
}
else {
    $(img).on('load',doneCallback);
}

UPDATE

If you change the code around, it will consistently fire a load event in all browsers.

var img = new Image();
$(img).load(doneCallback);
img.src = "foo.jpg";
Kevin B
  • 92,700
  • 15
  • 158
  • 170
  • If the browser has the image cached, will it definitely load directly after setting the src (without executing the load-check first)? – Cameron Martin May 01 '12 at 22:08
  • Yes, but it may not trigger the load callback. That is why we first check if it is done loading already. If it is already done loading, the load event may not trigger, so we don't bind it. – Kevin B May 01 '12 at 23:10
  • What about if the load event is bound before changing the image src? Would this cause the load event to always fire? – Cameron Martin May 02 '12 at 10:14
  • 2
    @ddlshack Note: It actually will always fire the load event if you first bind the load event, then change the source. – Kevin B May 30 '12 at 14:22
  • this does not work in safari 6 or IE9 and IE10 (IE8 works). they will always give false for img.complete || img.readyState === 4 even when the image is cached. i would love to have a working solution for these browsers. – Hans Aug 27 '13 at 05:41
  • @Marcel did you try the updated solution? (the one at the bottom that doesn't rely on complete or readyState) – Kevin B Aug 27 '13 at 14:10
  • @KevinB yes, attaching the load listener before the src attribute makes the load fire in all browsers, but I mean the part with the check for the cached image. Its a different problem though I realize. Checking if an image comes from cache or network. But thats the problem I am trying to solve right now. – Hans Aug 27 '13 at 14:41
  • Well, you could try detecting how long it takes the image to load, if it loads in 0ms it's probably cached, though that obviously isn't fool proof. – Kevin B Aug 27 '13 at 14:43