Preload images using javascript

Last updated on February 8th, 2022 at 04:35 pm

Click to rate this tutorial!
[Total: 2 Average: 4.5]

Using this script we can preload an image in to the webpage and display it when needed. Once you click the Show Image button the image will display immediately with out any delay as it comes from the cache (preload). If your internet connection is slow then you can see the difference clearly. If you are in a fast net then try to connect to a heavy image to get the difference in speed.

Here is the complete code in order to Cache images using javascript .

<html>
<head>
<title>Image Caching from mistonline.in</title>
<script language='JavaScript'>
//refer mistonline.in for more detailed scripts
objImage = new Image();
function download(){
// preload the image file
objImage.src='https://demo.mistonline.in/images/1.jpg';
}
function displayimage(){
document.images['im'].src = 'https://demo.mistonline.in/images/1.jpg';
}
</script></head>
<body onLoad='download()'>
<form name='f1'>
<img name='im' src=''/><br />
<input type='button' name='Prev' value=' Show Image ' onClick='displayimage()'/>
</form>
</body>
</html>

Now check out our JavaScript image slide show.

If you take a closer look at the browser developer tools, under “Network” tab we can see the image is preloaded as shown below (before clicking the “Show Button”)

Demo

Click to rate this tutorial!
[Total: 2 Average: 4.5]

Leave a Reply

Your email address will not be published.