Usually high resolution images can really slow down the website. images are loaded only after an HTTP request is sent for them, either passively via an <img> tag or actively through a method call. Preloading images comes to our rescue which means loading an image into cache before being used. The simplest way to preload an image is to instantiate a new Image() object in JavaScript and pass it the URL of the image you want preloaded.
The following example demonstrates the preloading of images:
JavaScript Preload Images Example
<!DOCTYPE html> <head> <TITLE>Example- preloading of images</TITLE> <script language = "JavaScript"> function preloader() { heavyImage = new Image(); heavyImage.src = "image.jpg"; } </script> </head> <body onLoad="javascript:preloader()"> <a href="#" onMouseOver="javascript:document.image.src='image.jpg'"> <img name="img01" src="image.jpg"></a> </body> </html>
Note that the image tag does not itself handle onMouseOver() and onMouseOut() events. Hence <img> tag in the example above has been enclosed in an <a> tag, which does include support for those event types.
Preload Images In JavaScript Demo
- Save the file as preloading.html in your system.
- Just open the file in the browser, you will notice how the image gets loaded fast.