11

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 and 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
    });
})
2
  • What are you trying to do, preload your image before showing? Commented Mar 6, 2010 at 12:25
  • Actually I just want it to fade in.. When I click on the image, set it's display to none and load. When load complete, fade in. Commented Mar 6, 2010 at 12:30

4 Answers 4

44

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 - Welcome! To answer your other question: The browsers I know of are Opera, Firefox, IE...but that may not be the whole list.
This is what I was looking for! It works on Android browsers too.
4

You need to be careful when using the load event for images since if the image is found in the browser's cache IE and (I am told) Chrome will not fire the event as expected.

Since I had to face this problem myself, I solved by checking the DOM attribute complete (said to be working in most major browsers): if equals to true I just unbinded the previously bound 'load' event. See example:

$("#myimage").attr("src","http://www.mysite.com/myimage.jpg").load(doSomething);

if ($("#myimage").get(0).complete) {

    // already in cache?
            $("#myimage").unbind("load");
            doSomething();


}

Hope this helps

Comments

1

I wanted this functionality and definitely did not want to have to load all the images when the page renders. My images are on Amazon s3 and with a big photogallery, that would be a lot of unnecessary requests. I created a quick jQuery plugin to handle it here:

$("#image-1").loadImage('/path/to/new/image.jpg',function(){  
  $(this).css({height:'120px'});//alter the css styling after the image has loaded
});

So basically, whenever a user clicks on a thumbnail that represents a set of pictures, I load the other images at that point in time. The callback allows me to change the css after the image has loaded.

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.