Page 1 of 1
JavaScript preload images ready for use
Posted: Sat Jun 19, 2004 5:35 pm
by Chris Corbyn
Hi,
Does anyone know how you can get get JavaScript to download any images as the page loads but not display them so that when they are called for rollovers they respond quickly, even with large images?
Thanks in advance

Posted: Sat Jun 19, 2004 5:47 pm
by feyd
there are many examples to be found using the almighty Google.. however, here's a basic example of what to do:
Code: Select all
<scirpt language="Javascript">
var preload1_over = new Image();
preload1_over.src = "/path/to/image.jpg";
var preload1_out = new Image();
preload1_out.src = "/some/other/image.jpg";
function swap(replace_image_name, replace_with_object)
{
if(document.images && document.imagesїreplace_image_name] && replace_with_object)
{
document.imagesїreplace_image_name].src = replace_with_object.src;
}
}
</script>
...
<a href="foo.html" onmouseover="swap('foobar',preload1_over)" onmouseout="swap('foobar',preload1_out)"><img name="foobar" src="/some/path/foo.jpg" /></a>
Posted: Sat Jun 19, 2004 9:17 pm
by Chris Corbyn
Thanks,
So is it pretty much a case that if the image is assigned to a variable, even if it's not displayed it will be stored in memory? And the same goes for other objects too....
JavaScript is really weird for me to understand after starting out with PHP/ASP and moving into an object oriented client side language. There's so much of it!
Thanks again
Posted: Sat Jun 19, 2004 9:59 pm
by feyd
yeah.. your browser will fetch the image(s) as soon as you set .src to something.. that includes ones that aren't an image somewhere already.. however, you may get some browser traffic if your cache size is small/page is large..
page cache settings apply too.. so if you set no-cache or whatever, you'll probably always get a new image from the server..