JavaScript Preloading

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.

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