Can you tell me if the function I wrote below is enough to preload images in most if not all browsers commonly used today?
function preloadImage(url)
{
var img=new Image();
img.src=url;
}
I have an array of imageURLs that I loop and call the preloadImage function for each URL.
Try this I think this is better.
Source: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
Here is my approach:
Yes. This should work on all major browsers.
I recommend you use a try/catch to prevent some possible issues:
OOP:
Standard:
Also, while I love DOM, old stupid browsers may have problems with you using DOM, so avoid it altogether IMHO contrary to freedev's contribution. Image() has better support in old trash browsers.
In my case it was useful to add a callback to your function for onload event:
And then wrap it for case of an array of urls to images to be preloaded with callback on all is done: https://jsfiddle.net/4r0Luoy7/
This approach is a little more elaborate. Here you store all preloaded images in a container, may be a div. And after you could show the images or move it within the DOM to the correct position.
Try it here, I have also added few comments