Is the function I wrote below enough to preload images in most, if not all, browsers commonly used today?
function preloadImage(url)
{
var img=new Image(
I can confirm that the approach in the question is sufficient to trigger the images to be downloaded and cached (unless you have forbidden the browser from doing so via your response headers) in, at least:
To test this, I made a small webapp with several endpoints that each sleep for 10 seconds before serving a picture of a kitten. Then I added two webpages, one of which contained a tag in which each of the kittens is preloaded using the
preloadImage
function from the question, and the other of which includes all the kittens on the page using
tags.
In all the browsers above, I found that if I visited the preloader page first, waited a while, and then went to the page with the
tags, my kittens rendered instantly. This demonstrates that the preloader successfully loaded the kittens into the cache in all browsers tested.
You can see or try out the application I used to test this at https://github.com/ExplodingCabbage/preloadImage-test.
Note in particular that this technique works in the browsers above even if the number of images being looped over exceeds the number of parallel requests that the browser is willing to make at a time, contrary to what Robin's answer suggests. The rate at which your images preload will of course be limited by how many parallel requests the browser is willing to send, but it will eventually request each image URL you call preloadImage()
on.