5

I have a coverflow plug-in for jQuery, which should adjust to the tallest image from a series of images.

Currently it uses a .load() binding on each image and adjusts the plug-in after a counter indicates all images have been loaded. I've been told this isn't reliable on all browsers, though.

Typically, most of these images will already be loaded in the browser cache, so the .load() binding is triggered a lot more than necessary.

In order to reduce the overhead I'd like to reduce the number of .load() bindings as much as possible by only using the .load() binding on images which have not yet been loaded.

How can you distinguish images that have already been loaded from images that have not yet been loaded?

Martijn
  • 3,696
  • 2
  • 38
  • 64
  • What about using localstorage, keeping track on any server update (new images or whatever and using some logic server side) to check if old images already in cache? Anyway, see: http://stackoverflow.com/questions/7844982/using-image-complete-to-find-if-image-is-cached-on-chrome – A. Wolff Nov 17 '14 at 20:12
  • Not quite a duplicate; the other question assumes the answer to this question is already known. – Martijn Nov 17 '14 at 20:37
  • The other answer is exactly the same logic you are using (even handling older browsers where `complete` property can be an issue) in your interresting comment in Guffa's answer. Sorry if i miss something but quite sure it is a duplicate, otherwise, my bad – A. Wolff Nov 17 '14 at 20:42
  • The point is; if you're looking for a way to see if an image is loaded and you don't know about `complete`, will you find the other question? I didn't. – Martijn Nov 17 '14 at 20:46
  • Ya a good point even i found it without using complete specific word: "check image cache javascript" in google. And marking question as duplicate doesn't mean question was useless or bad – A. Wolff Nov 17 '14 at 20:55

1 Answers1

8

Check the complete property of the image before binding the event. Example:

var img = $('.someImage');
if (img.prop('complete')) {
  // already loaded
} else {
  img.load(function(){
    // now it has loaded
  });
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • `img.prop('complete')` will work only on first matched element – A. Wolff Nov 17 '14 at 20:23
  • 2
    I ended up with something like `$('img').filter(function() { return !$(this).prop('complete'); }).load(...);`, which seems to work perfectly. Saves about a third of duplicate calculations. – Martijn Nov 17 '14 at 20:26
  • 1
    @A.Wolff: Yes, the code handles only one image, I hope that the answer didn't give any other impression. – Guffa Nov 17 '14 at 20:30
  • @Guffa I have always the 'impression' to expect more than one element when i see a class selector, quite my bad indeed :) – A. Wolff Nov 17 '14 at 20:32