Tuesday, May 4

Preloading images with jQuery

Hey.
I'm putting final touches on one web project and since we decided to put some pretty uncommon solutions into it without using flash I had to use many images and javascript tricks. jQuery is still so great for all those effects and manipulations...
And since some of the images are hidden at the beginning and exposed later, the browser downloads every single one of them only when it's needed. Sadly that's not the effect we want. The animations aren't smooth enough or foreground appears sooner than background etc.
The answer was - image preloading.
I've used image preloading techniques before, but they were so...last decade and lame :) I entered my query into google and got many suggestions. Most of them were based on selecting IMG tags and preloading SRC attribute values. At first that sounds fine, except that...some of images I want to preload aren't used as IMG SRC attributes. Moreover, most of the images don't need to be uploaded.
And finally I found the solution I actually applied. The idea is simple - creating IMG DOM elements for every image needed preloading. That's it.
We decide what to preload and the method takes care of the rest.
Actually the images I preload are loaded even before the ones that are visible at the beginning!
All you need is this piece of javascript code (and jQuery of course):


(function($) {
  var cache = [];
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)


Then you just call the function we just declared with arguments - relative paths to images you want to preload (as many as you need):

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");

That's it. Both image1.gif and image2.png will be preloaded into browser cache and won't waste time loading when actually shown for the first time.
I hope you'll find this usefull.
Good luck.

The solution taken from: http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript

1 comments:

Anonymous said...

Just want to say what a great blog you got here!
I've been around for quite a lot of time, but finally decided to show my appreciation of your work!

Thumbs up, and keep it going!

Cheers
Christian, iwspo.net

Google