faqts : Computers : Programming : Languages : JavaScript : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

16 of 20 people (80%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Image Url loading

Dec 21st, 2000 14:31
Juergen Thelen, Kirederf,


The question is. 
To preload an image you do
img=new Image();
img.src='image.jpg' of whatever.
now Admit I've a images folder with all my pictures img1.jpg, img2.jpg
I want to preload it.
Can I do in my preload method ?
img=new Image();
img.src='http://www.whatever.com/images/img1.jpg';
And can I be sure that when I specify
<img src="./img/img1.jpg"> or
<img src="../img/img1.jpg">
I display the image I preload previously.
It seems not cause it's pretty slow to display an image I've previously 
downloaded, so how can I be sure ?
Thanks all of you guys !
#####
Hi Frederik,
Q1: "Can I do in my preload method ?"
No, you can't.
To preload a series of continously numbered images just use an array of 
images and loop your preload. Heres a sample:
var lastpicnum = 22;
var ImgArray = new Array();
for (var i=1; i < lastpicnum; i++)
{
  ImgArray[i] = new Image();
  ImgArray[i].src = "../img/img"+i+".jpg";
}
This sample will try to preload img1.jpg, img2.jpg, ... to img22.jpg
Q2: "And can I be sure that when I specify..."
No, you can't either.
That's because you don't do a real preload there. What you do is to 
reference the file on the webserver again, which will slow down things.
It'll be of course faster than the initial download of each pic if the 
browser has cached it once, but you could further improve your 
performance, if you preload your images in a memory array like ImgArray 
and the just copy ImgArray[i].src to your target image source to be 
viewed.
This will be faster because you address a memory reference now and no 
web server reference anymore. The browser will just do a fast memory 
copy then...
Btw, keep in mind that preloading a series of images like in the sample 
above will start asynchronous downloads, meaning the browser will just 
start a download job for each pic and then immediately continue 
excecuting your html/js code. So before showing your preloaded pics 
make sure that they already have been loaded completely...
You can check this by each images ImgArray[i].complete() method...
Hope this helps.
Juergen