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(
Most answers on this post no longer work - (atleast on Firefox)
Here's my solution:
var cache = document.createElement("CACHE");
cache.style = "position:absolute;z-index:-1000;opacity:0;";
document.body.appendChild(cache);
function preloadImage(url) {
var img = new Image();
img.src = url;
img.style = "position:absolute";
cache.appendChild(img);
}
Usage:
preloadImage("example.com/yourimage.png");
Obviously Use this in your CSS, instead of applying the If you have tested this, please leave a comment. Notes: While above solution works, here's a small update I made to structure it nicely: (This also now accepts multiple images in one function) Preview: Notes:
is not a "defined" element, so you could use a style
attribute:cache {
position: absolute;
z-index: -1000;
opacity: 0;
}
cache image {
position: absolute;
}
display: none;
to cache - this will not load the
image.position: absolute
to the image is necessary, as the image elements will eventually make it's way outside of the viewport - causing them to not load, and affect performance.
UPDATE
var cache = document.createElement("CACHE");
document.body.appendChild(cache);
function preloadImage() {
for (var i=0; i