views:

878

answers:

2

I saw a comment on Ben Nadel's blog where Stephen Rushing posted a loader, but I can't figure out how I can pass the selectors and parameter.. I think I also need a completeCallback & errorCallback functions?

function imgLoad(img, completeCallback, errorCallback) {
    if (img != null && completeCallback != null) {
        var loadWatch = setInterval(watch, 500);
        function watch() {
            if (img.complete) {
                clearInterval(loadWatch);
                completeCallback(img);
            }
        }
    } else {
        if (typeof errorCallback == "function") errorCallback();
    }
}
// then call this from anywhere
imgLoad($("img.selector")[0], function(img) {
    $(img).fadeIn();
});

HTML:

<a href="#" class="tnClick" ><img id="myImage" src="images/001.jpg" /></a>

JS:

$(document).ready(function() {
    var newImage = "images/002.jpg";
    $("#myImage").css("display","none");
    $("a.tnClick").click(function() {
        // imgLoad here
    });
})
+1  A: 

If you want it to load before showing, you can trim that down a lot, like this:

$(document).ready(function() {
    var newImage = "images/002.jpg"; //Image name

    $("a.tnClick").click(function() {
      $("#myImage").hide() //Hide it
        .one('load', function() { //Set something to run when it finishes loading
          $(this).fadeIn(); //Fade it in when loaded
        })
        .attr('src', newImage) //Set the source so it begins fetching
        .each(function() {
          //Cache fix for browsers that don't trigger .load()
          if(this.complete) $(this).trigger('load');
        });
    });
});

The .one() call makes sure .load() only fires once, so no duplicate fade-ins. The .each() at the end is because some browsers don't fire the load event for images fetched from cache, this is what the polling in the example you posted is trying to do as well.

Nick Craver
Ooooh "Cache fix for browsers that don't trigger .load()"That was my concern (after reading that post)Do you know which browsers do not support .load?
FFish
sweet Nick, thanks so much!
FFish
@FFish - Welcome! To answer your other question: The browsers I know of are Opera, Firefox, IE...but that may not be the whole list.
Nick Craver
A: 

Hi!

Try this one? ...

doShow=function(){ if($('#img_id').attr('complete')){ alert('Image is loaded!'); } else { window.setTimeout('doShow()',100); } };

$('#img_id').attr('src','image.jpg'); doShow();

...

Seems like the above works everywhere...

Jay