|
|||||||
| JavaScript JavaScript (not Java) Discussion and technical support, including AJAX and frameworks (JQuery, MooTools, Prototype...) |
![]() |
|
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
image on preload
Hello everyone, I've been breaking my head over this seemingly simple problem. Basically, I need my website to wait for an image to preload before executing the next commands. To do this I create an image object, assign a src property and use the onload event to execute the next set of commands. Unfortunately onload doesnt seem to work. I've posted an example of the code:
<html> <head> <script language = "JavaScript"> function preloader() { heavyImage = new Image(); heavyImage.src = "upload/admiration.jpg"; heavyImage.onLoad = afterLoad (heavyImage) ; } function afterLoad (hi){ alert (hi.complete); alert (hi.height); } </script> </head> <body onLoad="javascript reloader()"></body> </html> When I ran this script in IE the output I got was hi.complete = false and hi.height = 0. If I ran the same script a second time with the same image file I still get hi.complete = false, but this time hi.height produces the correct height value of the image. When I ran this code in firefox, hi.complete was 'true' the first and second time I ran it, and hi.height produced 0 the first time I tried to preload the image and the actual height of the image when I ran the script a second time (with the same image). I am guessing that onload doesn't work properly and the output function is executed before the image loads, but I have no idea why, or how to go about solving this. I would really appreciate some help with this. Thanks. |
|
#2
|
|||
|
|||
|
Code:
function preloader(){
var heavyImage = new Image();
heavyImage.src = "http://www.vicsjavascripts.org.uk/StdImages/One.gif";
afterLoad(heavyImage,new Date()) ;
}
function afterLoad (hi,d){
if (hi.complete&&hi.width>50){
alert (hi.complete);
alert (hi.height);
}
else if (new Date()-d<5000) {
setTimeout(function(){ afterLoad (hi,d); },100);
}
else {
alert('unable to load after 5 seconds');
}
}
__________________
Vic God loves you and will never love you less. http://www.vicsjavascripts.org.uk remove any spaces between java & script |
|
#3
|
|||
|
|||
|
Thanks Vic! This works great!
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|