Using Client-Side Scripting to Preload Images with CSS and JavaScript
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.
Using Client-Side Scripting to Preload Images with CSS and JavaScript (Page 1 of 4 )
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!