Using jQuery to Preload Images with CSS and JavaScript
If you’re a web designer searching for a guide to implementing the most common graphic preloading methods available nowadays, then you've come to the right place. This five-part article series lets you accomplish this task by utilizing either a few basic style sheet properties or the functionality provided by client-side scripting. In this fifth part of the series, we'll employ the jQuery JavaScript library to assist in preloading our images.
Using jQuery to Preload Images with CSS and JavaScript - Abstract the image preloading process with jQuery (Page 3 of 4 )
If you're ever worked with the jQuery library, you know that it allows developers to perform complex tasks by writing only a few lines of compact code, thanks to its famous fluent interface and its set of convenient methods. Well, I have to admit that creating an image preloader with jQuery isn't the most difficult challenge that can ever be faced, but the following script shows that the library turns this process into a no-brainer. Check it out:
$(document).ready(function () {
var images = ['sample_image1.jpg', 'sample_image2.jpg', 'sample_image3.jpg', 'sample_image4.jpg', 'sample_image5.jpg'];
$(images).each(function(key, value) {
var img = new Image();
$(img)
.attr('src', value)
.error(function (){
alert('Error preloading image ' . value);
})
});
});
That was really easy to code and read, right? As you can see, the implementation of the same image preloader that you saw in the previous segment has been improved considerably thanks to the functionality provided by jQuery. In this case, the library makes it easier to load a variable number of images, and permits you to handle errors in a slightly more graceful way.
So far, so good. At this point you've surely grasped how to create a graphic preloader with jQuery, so the last thing we need to do is include the earlier JavaScript snippet into a sample web page. That's exactly what I'm going to do in the section to come. So click on the link below and read the following lines.