Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if an image is loaded or cached in JQuery?

Tags:

jquery

Seems the .load() function doesn't fire if the image has been cached before. So if you want to make sure one images has loaded before you load and show another (i.e. Magnifier) you can't do something like:

$(img_to_load_first)
    .load(
        $(img_to_load_last)
            .src("2nd.png");
    )
    .src("1st.png");

So how does one ensure loading order in JQuery?

like image 945
CpILL Avatar asked Dec 22 '09 19:12

CpILL


1 Answers

What you'll have to do is handle your load bindings selectively. You can verify load by testing the Image object property complete.

For example:

$('.load_selector').each(function(){

    if (!this.complete) {
        $(this).load(function(){
            // handle image load event binding here
        });
    } else {
        // handle image already loaded case
    }

});

Note that above, this (used alone) refers to the DOM reference to the image object provided by jQuery.

like image 151
sparkey0 Avatar answered Sep 22 '22 16:09

sparkey0