Precaching images with JavaScript

Most of the time images on your page take extra seconds to download from web server. Again if you want to load some images on some user action, you most likely want the fast image load i.e. instant with the user clicks..
Or in case you want to create an image gallery viewer by clicking ‘Next’ / ‘Previous’, you usually don’t want waiting your user for some extra seconds for each image loading.

JavaScript helps you to load images into the browser’s memory cache without displaying them.This technique is the hilarious precaching images. And this technique preload the images into the browser cache when the page initially loads.

In order to precache an image we need to construct an image object in memory. Image object created in memory is dissimilar from the document image object aka <IMG>tag.

Here we go

var myImage = new Image(width, height)

Parameters to the constructor are the pixel width and height of the image we want to precache.
So the image object exists in memory. Now you can assign a filename or URL to the src property of that image object:

myImage.src = “someImage.jpeg”

Such above statement assigning image src loads the image into the browser image cache.

Now you can use this cached image wherever you like instantly.
You may assign this precached image src property to the actual document image tag src property.

document.images[0].src = myImage.src

Here is the detail example:

<html>
<head>
<title>Image viewer</title>
<script type="text/javascript">

//precache four images
image1 = new Image(480, 320)
image1.src = "1.jpg"
image2 = new Image(480, 320)
image2.src = "2.jpg"
image3 = new Image(480, 320)
image3.src = "3.jpg"
image4 = new Image(480, 320)
image4.src = "4.jpg"

//loads an image from cache
function loadFromCache(img){
	document.imagePlaceHolder.src = eval(img + '.src')
}
</script>
</head>

<body>

<div align="center">
<img name="imagePlaceHolder" src="1.jpg">

<br>

<a href="#" onClick="loadFromCache('image1')">Image1</a>
<a href="#" onClick="loadFromCache('image2')">Image2</a>
<a href="#" onClick="loadFromCache('image3')">Image3</a>
<a href="#" onClick="loadFromCache('image4')">Image4</a>

</div>
</body>
</html>

In the above example four images are precahced into browser memory and used in the page <IMG> tag src property oncilck on the four links instantly updates the document <IMG> tag src. Try the example and feel the difference in image loading. :)

Download this example code with some sample images

Tadddaaaa!