JavaScript preload images ready for use

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

JavaScript preload images ready for use

Post 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 :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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)
&#123;
  if(document.images && document.images&#1111;replace_image_name] && replace_with_object)
  &#123;
    document.images&#1111;replace_image_name].src = replace_with_object.src;
  &#125;
&#125;
</script>

...

<a href="foo.html" onmouseover="swap('foobar',preload1_over)" onmouseout="swap('foobar',preload1_out)"><img name="foobar" src="/some/path/foo.jpg" /></a>
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.... :idea:

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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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..
Post Reply