Advertisements
In this fourth part of a series, I demonstrate that preloading a group of images with JavaScript is an easy-to-master process, especially if you already have an intermediate background in manipulating the DOM via client-side scripting. Note that the biggest drawback to the approach is its dependence on JavaScript to do its thing; you should keep this in mind when implementing this type of image preloading mechanism on your own web pages.
Usually, the term "eager loading" is used to refer to a well-known design pattern, often implemented in desktop and web-based applications. As its name implies, the pattern permits a given program to load a specific resource, be it a database result set, a class instance or an XML file in anticipation of need, regardless of whether the resource is used during the program's execution.
While at first sight eager loading seems to be pretty pointless, under certain conditions it can be useful for improving the performance of an application. A good example that shows the benefits of using eager loading is a web program that displays blog entries and comments: apart from pulling records from an "entries" database table, the program could eventually "prefetch" in the background all of the comments associated with each entry. Get the point? I bet you do.
Considering the previous example, you may feel inclined to think that eager loading can only be applied on the server side. Actually, the same concept can be used when rendering web pages, and more specifically when displaying online images. In fact, today there are some popular techniques that allow you to preload images easily, either with CSS or JavaScript, which lets users see them with no visible delay.
To illustrate how to use eager loading for showing images on screen, in previous installments of this series I went through the development of a few basic methods for preloading a set of sample graphics. I made clever use of the "background-image" CSS property.
While it's valid to point out that one group of these methods required the coding of additional markup, which doesn't speak very well about their efficiency, all of them relied on the functionality of CSS to work properly. This doesn't mean, however, that style sheets are the only way to preload images in the background. In fact, it's possible to produce similar results using plain JavaScript.
Therefore, in this fourth chapter of the series I'm going explain how to use some native JavaScript code to implement a rudimentary, yet functional, image preloading mechanism. Ready to learn the full details? Then let's get started!
Undoubtedly, one of the most effective techniques to use for preloading sets of images in the background takes advantage of the "background-image" CSS property to hook the images to existing containers within a web page. This approach permits you to achieve the desired goal without having to write portions of non-semantic markup. The following example, which was developed in the previous installment of the series, shows how to implement this in a few simple steps:
<!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 CSS (no additional markup is required)</title>
<style type="text/css">
body {
padding: 0;
margin: 0;
background: #000080;
font: 1em Arial, Helvetica, sans-serif;
color: #000;
}
#wrapper {
width: 960px;
margin: 0 auto;
background: #eee;
}
/* the header, content and footer containers are used as hooks to preload images */
#header {
padding: 10px;
background: url("sample_image1.jpg") -9999px -9999px no-repeat;
}
#content {
padding: 10px;
background: url("sample_image2.jpg") -9999px -9999px no-repeat;
}
#footer {
padding: 10px;
background: url("sample_image3.jpg") -9999px -9999px no-repeat;
}
/* sample images */
img {
padding: 10px;
background: #fff;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Preloading images using CSS (no additional markup is required)</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>
</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>
From the above example, it's clear to see that when used intelligently, the "background-image" property can be very helpful for preloading multiple images behind the scenes. In this case, only three graphics have been attached to different sections of the web page, but naturally it's possible to preload a few more, depending on your specific needs.
So far, so good. Now that you've learned how the prior approach works, it's time to explore other preloading methods, so you can choose the one that best fits your requirements. Thus, in the following section I'm going to demonstrate how to create a simple prefetching method similar to the one that you just saw, but this time using some basic JavaScript.
To learn more about how this will be done, click on the link below and read the lines to come.
I don't want to sound arrogant, but preloading images with JavaScript is a ridiculously simple task. Essentially, the process requires that you first create an image container in memory, and then fill it with the loaded image. Of course, my words must be backed up by functional code, so below I've created a short JavaScript snippet that will preload in the background a set of five images. Take a look at it:
<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>
Didn't I tell you that preloading pictures with JavaScript was a breeze? Well, this simple script shows that in a nutshell. As you can see, it simply requests the pertinent images via the "src" attribute provided by the DOM and nothing else. Needless to say, the snippet should be always included on top of the web page, so all of the images will be available to be displayed afterward.
All right, having demonstrated how to implement a trivial preloading mechanism using only plain JavaScript, the next step is to include the preloader in an XHTML document, so you can test it and introduce your own improvements. That's exactly what I'm going to do in the last segment of the tutorial, so click on the link below and keep reading.
If you're anything like me, you want to see for yourself if the image preloader developed in the preceding section really functions as expected. Below I coded a web page that includes this simple JavaScript-based mechanism, so you can give it a try on your own browser. 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>
Mission accomplished. At this point, the above image preloader is not only fully functional, but can easily be customized for prefetching any number of graphics. Despite these shining advantages, this method naturally suffers from the same problems of any JavaScript application: it can be turned off on the browser. I suggest you use it with caution, or even switch over to a CSS-based implementation.
Final thoughts
In this fourth part of the series, I demonstrated that preloading a group of images with JavaScript is an easy process that can be mastered with minor effort, especially if you already have an intermediate background in manipulating the DOM via client-side scripting. On the other hand, the biggest drawback of the approach shown before is its strong dependency on JavaScript to do its thing, so you should take this issue into account when implementing this type of image prefetching mechanism on your web pages.
Of course, if it's feasible to preload graphics in the background using plain JavaScript, this implies that the same task can be performed with jQuery as well. Therefore, the last part of the series will focus on explaining how to accomplish this with the popular JavaScript library.