Image Preloading is a technique, often used in navigation graphics and image rollovers, to load images and put them in the browser's cache before they are needed. In this post, we will focus on the Javascript technique to implement image preloading. Also, check another Javascript image preloading technique on Image Preloading with jQuery
The Javascript Image() Object
The simplest way to preload an image is to instantiate a new Image() object in Javascript and pass the URL of the image you want to preload.
For example, if you want to preload an image, simply create a new javascript Image() object and place the script in the head section of the page to ensure it runs as soon as the page loads.
<script type="text/javascript">
Image= new Image()
Image.src = "pic1.jpg"
</script>
PreLoading Multiple Images with Javascript Arrays
In practice, you will need to preload more than just one image to smooth effect on image rollovers. A Javascript array of images can be preloaded as:
<script type="text/javascript">
images = new Array();
images[0]="pic1.jpg"
images[1]="pic2.jpg"
images[2]="pic3.jpg"
// start preloading
for(i=0; i<=2; i++)
{
imageObj.src=images[i];
}
</script>
The JavaScript image preloading code may be placed anywhere in the HTML source code. If placed in the HEAD section, images would be loaded before any of the page content is displayed. Also consider checking another image pre-loading technique with CSS at Preloading Images Using CSS
Want automatic updates?
Subscribe to our RSS feed
or
Get Email Updates
sent directly to your inbox!
Currently rated 3.7 by 3 people
- Currently 3.666667/5 Stars.
- 1
- 2
- 3
- 4
- 5