Forum Moderators: not2easy

Message Too Old, No Replies

question about preloading images javascript

         

scorpion

7:22 pm on Mar 19, 2003 (gmt 0)

10+ Year Member



Does anybody know if you use this code:
image1on = new Image();
image1on.src = "graphics/contents/01hi.gif";

in a file, does this load the image in the browser's cache, thus if that file is used in a second file, it will be preloaded? Or does the above code ONLY load the image for that particular file and it is not in the cache subsequently?

Thanks

lorax

8:23 pm on Mar 19, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Javascript depends upon an event to trigger it so how the image gets loaded/cached will depend upon what the trigger is. If the trigger is the onLoad event applied to the <body> tag then it will be preloaded. If the trigger is a mouseOver event then it won't be preloaded but loaded at the time of the first mouseOver event. If the trigger is the creation of a function which calls the constructor Image() and passes the src to it then it will occur (I think) when the function is called but not before.

As for caching the image - if the same image is used with another call to the image object (ie: the src file name is the same) then the browser will use the cached image file.

scorpion

5:56 am on Mar 20, 2003 (gmt 0)

10+ Year Member



i have two files:

images.js - creates Image() object with src="graphics/image.jpg"
images_sub.js - creates Image() object with src="../graphics/image.jpg"

basically I have a navbar that I want to always load but sometimes it is in a subdirectory (i use the second version for the include in a subdirectoyr), so I'm wondering if when just one of the above files is loaded the first time, then for ANY file in any subdirectory including one or the other of the above src files, the file is loaded from the browser cache...

lorax

3:29 pm on Mar 20, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I think (operative word) that because the source path is different it will require a fresh load. Technically speaking - it is a different image.

Try a relative path like this: /subdir1/filename.ext. Note the leading '/'. In this case the path would never change regardless of what directory you called the image file from and therefore the image should be cached and re-used.