/usr/share

Dabblings in the webs and suchlike.

May 25

Prefetch Images With Javascript

This one is an oldie but a goodie. If you ever need to swap out the src on an image tag you can prefetch images with javascript to make the swap instant after the page loads. All you need to do is create an image element in javascript and assign the url to the src. The browser will request the image immediately regardless of what you do with the image element. You can try this out in the network tab of your browser dev tools:

image prefetch in dev console

Now you can assign the same url to an img tag in your html and the image will change immediately if it has finished loading in the background. You can also prefetch and swap out background images the same way.

try it out in this fiddle


Notes