Preload an Image using JavaScript

In this example, we preload an image by coding in javascript.
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. myimg = new Image();
  5. myimg.src = "two.gif";
  6. function ChangeTheImg() {
  7. document.getElementById('myfrstImage').src = myimg.src;
  8. }
  9. </script>
  10. </head>
  11. <body>
  12. <img id="myfrstImage" onmouseover="ChangeTheImg()" src="One.jpg" width="100" height="100">
  13. </body>
  14. </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.