Preload an Image using JavaScript

Preload an Image using JavaScript

 
In this example, we preload an image by coding in javascript.
  1. <html>  
  2.   
  3.    <head>  
  4.       <script type="text/javascript">  
  5.       myimg = new Image();  
  6.       myimg.src = "two.gif";  
  7.   
  8.       function ChangeTheImg() {  
  9.          document.getElementById('myfrstImage').src = myimg.src;  
  10.       }  
  11.       </script>  
  12.    </head>  
  13.   
  14.    <body>  
  15.       <img id="myfrstImage" onmouseover="ChangeTheImg()" src="One.jpg" width="100" height="100">  
  16.    </body>  
  17.   
  18. </html> 
In this program, we call the function ChangeTheImg()  by which we set the source of the previous image.
  1. document.getElementById('myfrstImage').src=myimg.src; 
when we put the mouse over on the previous image the function is called. It takes no time as the second image is already loaded by the browser.
Ebook Download
View all
Learn
View all