Friday, February 27, 2009

Preload images with jQuery

Web2.0 came with AJAX and AJAX came with its own requirements and standards for web application developers. Now web applications are more like desktop applications with a lot of options, dialogs and more. If you have developed AJAX application with different user controls you surely loaded resources such images, other javascript files on demand. This helps you keep your application lightweight and makes its load time faster.

jQuery makes creation and loading DOM elements (in our case images) very easy. If you need to preload an image you can use this jQuery script here:

// Create an image element
var image1 = $('<img />').attr('src', 'imageURL.jpg');

First jQuery creates a image DOM element and setting the src attribute of the image element would tell the user browser to load that image. Thus preloading the image.

Next you should insert your DOM element into the DOM tree using one of the many jQuery DOM manipulation methods.

Here are some examples of how you could insert preloaded image into your website:

var image1 = $('<img />').attr('src', 'imageURL.jpg');

// Insert preloaded image into the DOM tree
$('.profile').append(image1);
// OR
image1.appendTo('.profile');

But the best way is to use a callback function, so it inserts the preloaded image into the application when it has completed loading. To achieve this simply use .load() jQuery event.

// Insert preloaded image after it finishes loading
$('<img />')
    .attr('src', 'imageURL.jpg')
    .load(function(){
        $('.profile').append( $(this) );
        // Your other custom code
    });

Similar how to’s:

21 comments:

  1. Did you test the load functionality, as it does not work for me. The load even never gets fired in Firefox or IE.

    ReplyDelete
  2. I just did, and it is working fine in Firefox/IE.

    You need to insert the loaded image in to your DOM tree on callback like this:

    $('body').append( $(this) );

    Here I am appending it to the HTML body tag. Examples above append it to the '.profile' div/container.

    ReplyDelete
  3. Cool - I never thought about using a new DOM element's 'load' event

    ReplyDelete
  4. Helped me a lot, thank you! Great explanation, easy to understand for a jQuery beginner like me.

    ReplyDelete
  5. What happens if JavaScript is turned of in the user's browser?

    ReplyDelete
  6. nice job, great coverage of the various options

    ReplyDelete
  7. More importantly this is great to use on a login page to load images that show up on the page immediately following. I expect I can save the user waiting for 10 or more HTTP requests and 50kb to download when they're waiting for their data to show up, and have it load in a place where they browser is waiting for them. Just skip the part where you append the images to the DOM, the browser will have them cached for use on the next page which will return "304 Not Modified" headers in place of the images.

    ReplyDelete
  8. What about if you want to run your "other custom code" after several images finish loading!?

    ReplyDelete
  9. Quick and dirty, just the way I like it. Thanks for the tip!

    ReplyDelete
  10. @Marco, you can set some counter and check for it in all your callback functions.

    @Anonymous, if user's browser has js turned off, then this would not work!

    ReplyDelete
  11. // First Attach the load function to load event of image as below.
    $('<img />')
    .load(function(){
    $('.profile').append( $(this) );
    });
    .attr('src', 'imageURL.jpg')

    ReplyDelete
  12. If the load event handler isn't being fired, it's because the image has loaded completely before you attach the event handler. This should fix it:

    $('< img />') //Remove the space after "<"
    .load(function(){
    $('.profile').append( $(this) );
    // Your other custom code
    })
    .attr('src', 'imageURL.jpg');

    ReplyDelete
  13. Dude, this is awesome! I'm using Google's Chart API to load some charts onto my page, and sometimes these charts take long to load. Therefore, I'm putting a div over it first with a spinner, however I needed a way to know when the image is done loading, so I can hide the spinner, and show the image. This worked perfectly, thanks!

    ReplyDelete
  14. I don't understand..
    What i have to put in html file?

    Thank you

    ReplyDelete
  15. mmmhhh.... :)

    So, it's now easy to load an image into background-image like this :

    $("#myDiv").css({'display:'none'});

    var img = new Image();

    $( img ).load(function()
    {
    $("#preload").css({display:'none'});
    $("#myDiv").css({ 'background-image':'url('+src+')' }).fadeIn();
    })
    .error(function()
    {
    // notify the user that the image could not be loaded
    })
    .attr('src', src );

    ReplyDelete
  16. myImage = new Image(); myImage.src = "/path/to/image.jpg";
    Wondering if the oldschool way is still valid, seems to work in the browsers I tested.

    ReplyDelete
  17. Hi,

    thanks for this, saved me a lot of time.

    Cheers,
    Marek

    ReplyDelete
  18. In my testing, this code does not close the img tag.

    ReplyDelete
  19. can any one tell where i have to add this code in .html file or in java script....

    ReplyDelete