Advertisements
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.
Even though the topic seems intimidating and somewhat obscure, preloading images on web pages is a fairly straightforward process that can be mastered with only an average background in CSS and JavaScript. That's all you need, really.
Of course, if you've been a patient reader of the series and already went through all of the parts previous to this one, then you now have solid knowledge of how to use a combination of CSS and JavaScript to create some simple, yet functional, image preloading mechanisms on your own (X)HTML pages. In the course of those tutorials I demonstrated how to accomplish this with a decent variety of code samples.
To be more specific, I left off the last tutorial showing how to prefetch a set of sample images in the background by using just plain JavaScript, which speaks for itself about the simplicity of this process. However, the trends that rule the world of modern web design say that if something can be done with native JavaScript, it's quite probable that the same results can be obtained using the level of abstraction offered by jQuery. In keeping with this idea, in this last installment of the series, I'm going to demonstrate how to develop a small image prefetching application, which will base all of its functionality on the jQuery library to do its business.
Ready to tackle the final chapter of this hopefully educational journey in preloading images with CSS and JavaScript? Then don't hesitate anymore; click on the link below and jump in!
Using jQuery to Preload Images with CSS and JavaScript - Review: creating an image preloader mechanism with plain JavaScript
(Page 2 of 4 )
As I mentioned, implementing a basic image preloader using plain JavaScript is an extremely simple task. It only requires doing some DOM manipulation and nothing else. The full details of this process were covered in the previous part of the series, but in case you still haven't read that installment, below I listed for you the source code corresponding to this particular example. Here it is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Preloading images using plain JavaScript</title>
<script type="text/javascript">
// check to see if the browser accepts images and understands the DOM
if (document.images && document.getElementById && document.getElementsByTagName) {
// preload images
var image1 = new Image();
image1.setAttribute('src', 'sample_image1.jpg');
var image2 = new Image();
image2.setAttribute('src', 'sample_image2.jpg');
var image3 = new Image();
image3.setAttribute('src', 'sample_image3.jpg');
var image4 = new Image();
image4.setAttribute('src', 'sample_image4.jpg');
var image5 = new Image();
image5.setAttribute('src', 'sample_image5.jpg');
}
</script>
<style type="text/css">
body {
padding: 0;
margin: 0;
background: #000080;
font: 1em Arial, Helvetica, sans-serif;
color: #000;
}
/* main containers */
#wrapper {
width: 960px;
margin: 0 auto;
background: #eee;
}
#header, #content, #footer {
padding: 30px;
}
/* sample images */
img {
padding: 10px;
background: #fff;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Preloading images using plain JavaScript</h1>
<h2>Header section</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<div id="content">
<h2>Main content section</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p><img src="sample_image1.jpg" width="400" height="300" alt="Sample Image 1" /></p>
<p><img src="sample_image2.jpg" width="400" height="300" alt="Sample Image 2" /></p>
<p><img src="sample_image3.jpg" width="400" height="300" alt="Sample Image 3" /></p>
<p><img src="sample_image4.jpg" width="400" height="300" alt="Sample Image 4" /></p>
<p><img src="sample_image5.jpg" width="400" height="300" alt="Sample Image 5" /></p>
</div>
<div id="footer">
<h2>Footer section</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
</body>
</html>
As the above code fragment demonstrates, the implementation of a basic image preloading mechanism with JavaScript is a two-step process. It demands, first, the creation of a new image object for each graphic being loaded, and second, filling the object with the image in question, in this case using the "src" attribute. Is there anything simpler to grasp than this approach? I don't think so.
But before you move on, let's analyze the previous script more closely. Obviously, there's plenty of room to improve it and make it slightly more flexible. The first enhancement that comes to my mind is the inclusion of an iterator that allows you to traverse collections of image objects for easier manipulation.
Logically, this can be done using native JavaScript methods and properties, but in this case I'm going to show you how to produce the same result with jQuery. This will not only make the whole preloading process a bit more abstract, but it'll permit you to handle potential errors, at least at a basic level.
To see how I plan to develop this jQuery-based image preloader, click on the link below and read the following section.
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.
To get this jQuery-based image preloader up and running, the final step we must take is to bind the previous JavaScript code to the structure of a web page. To keep things uncluttered and easy to follow, in this example I'm going to use the same XHTML document shown in other tutorials of this series, which featured the typical header, content and footer sections.
In summary, the finished version of the preloader will look as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Preloading images using jQuery</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(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);
})
});
});
</script>
<style type="text/css">
body {
padding: 0;
margin: 0;
background: #000080;
font: 1em Arial, Helvetica, sans-serif;
color: #000;
}
/* main containers */
#wrapper {
width: 960px;
margin: 0 auto;
background: #eee;
}
#header, #content, #footer {
padding: 30px;
}
/* sample images */
img {
padding: 10px;
background: #fff;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Preloading images using jQuery</h1>
<h2>Header section</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<div id="content">
<h2>Main content section</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<div id="footer">
<h2>Footer section</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
</body>
</html>
Done. At this stage, it's safe to say that the image preloader is finally ready to be put into action. So, I suggest that you create your own sample images or simply utilize the ones shown in the first part of the series and give the above script a try on your machine. If you have the chance to use a Firefox extension like Firebug or HTTP Live Headers to examine the set of HTTP requests and headers exchanged between the browser and the web server, you'll see that the preloader works remarkably well.
Final thoughts
Unfortunately, we've come to the end of the series. Nevertheless, the experience has been educational and why not, also fun, since you learned a few useful approaches that can be easily implemented on a web page for preloading images in the background. For obvious reasons, I'd recommend that you use only the ones that don't require you to code additional, non-semantic markup. However, if you feel more comfortable working with JavaScript-based preloaders, make sure they will stick neatly to the rules of progressive enhancement or graceful degradation.