views:

38

answers:

3

I have this code:

if (document.images)
    {
      preload_image = new Image(25,25); 
      preload_image.src="http://mydomain.com/image.gif"; 
    }

First of all, will this work in all major browsers?

Secondly, do I need to specify the width and height like in the code?

Lastly, will this preload my images and cache them?

Thanks

+1  A: 

It will work in all major browsers. You do not have to specify dimensions, just a source ('src'), as you do up there.

Here's an example where dimensions are not given, and it works just fine: http://www.yourhtmlsource.com/images/rollovers.html

Robusto
Will it work if I put a preload_function in the "Body onload=preload_images()"... Will the browser preload images everytime the user clicks refresh? or the back button to the page with the body_onload=preload tag?
Camran
It will first check them against the cache. If they are cached, they will not be downloaded; if not, they will.
Robusto
Okay, last thing. I currently display some images like this: "style.backgroundImage = 'url(Graphics/lvl4.gif)';" If I have preloaded an image and like this: "img1 = new Image(); img1.src='Graphics/lvl4.gif';" Do I then need to call the img1 variable instead of the path to the image in the backgroundImage url? like url(img1)?
Camran
Just keep it with the url(path-string) methodology. That's all the browser does, just checking the path identifier URL against the cache. If it's in the cache, it will be displayed, no matter if it's in CSS or in an HTML `<img>` tag.
Robusto
A: 

Hey Camran,

Yes this will preload the image, and no you don't need to specify the size as new Image() should be enough.

The main point to take away from your code snippet is the actual .src assignment as this should cause most modern browsers to fetch the file even though it's not actively displayed on the page.

Hope this helps,

Chris

Chris Gaudreau
A: 

If you want the preloading to work on all browsers you need to use a positive height and width (the minimum being 1x1).
You can reset the size of the image later using css or img attributes.

Knu