https://www.htmlgoodies.com/tutorials/web_graphics/article.php/3480001
JavaScript Preloading
JavaScript includes the Image among its native object types. The Image object represents an HTML image tag on the page and exposes the same properties and events. Perhaps oddly, the Image has no constructor that accepts an image source, so an image must be loaded into the object by setting its src attribute. Doing so causes the image to be downloaded from the server at that point.
1 2 3 4 |
<script type="text/javascript"> var my_image = new Image(); my_image.src = 'mycoolimage.jpg'; </script> |
Once an image is preloaded with JavaScript, you can take advantage of the cached image using only its filename. It’s not necessary to keep using the JavaScript variable that you loaded the image into. The thonky.com provides an excellent demo to illustrate this. The demo provides a button to preload the image. After it has finished loading, the page displays a second button that allows you to use the preloaded image in an image tag, using only the image filename. Even though the code does not refer to the variable that the image was loaded into, the image will still show up right away because it’s in the cache.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<script type="text/javascript"> var my_image2 = new Image(); // notify the user that the image has been preloaded, and reveal the // button to use the preloaded image function notify() { document.getElementById('preloadbutton2').style.display = 'none'; document.getElementById('after_preload').style.display = 'block'; } function preload() { my_image2.onload = notify; my_image2.src = 'bigsaturn.jpg'; } // using only the file name, we can take advantage of the preloaded image function use_preloaded_image() { document.getElementById('saturnplaceholder').src = 'bigsaturn.jpg'; } </script> <input type="button" id="preloadbutton2" value="Preload Image" onclick="preload();this.value='Loading. Please wait...'" /> <div id="after_preload" style="display: none"> <input type="button" value="Use Preloaded Image" onclick="use_preloaded_image()" /><br /> <img src="blank.jpg" id="saturnplaceholder" width="500" /> </div> |