Click to See Complete Forum and Search --> : Image properties not available until 2nd load


tjdrew
10-09-2003, 04:18 AM
:confused:
In the following extracts of code, the first time a browser views the image that repalces {BIG_IMAGE} the height and width attributes are 0, yet a refresh of the page will see the correct values loaded. If the page is revisited at a later time it will work first time from then on ....
the debug alert call makes no difference to the result. If the height and width are 0 then nothing is displayed.
I have see the same behaviour with IE 6.0, Netscape 7.1, Opera 7.11 and Mozilla 1.5 and am at a loss to prevent it.
Does anyone know of a work around/fix for this issue ?

-- in head of page

MaxWidth = 350;
MaxHeight = 450;
// Set default values
Iwidth = MaxWidth;
Iheight = MaxHeight ;

function L_ImageSize(iw, ih) {
rw = iw / MaxWidth;
rh = ih / MaxHeight;
if ( rw <= 1 && rh <= 1 ) {
Iwidth = iw;
Iheight = ih;
} // if
else if ( rw <= 1 && rh > 1 ) {
Iwidth = iw / rh;
Iheight = ih / rh;
}
else if ( rw > 1 && rh <=1 ) {
Iwidth = iw / rw;
Iheight = ih / rw;
}
else if ( rw > 1 && rh >1 ) {
if ( rw > rh ) {
Iwidth = iw / rw;
Iheight = ih / rw;
}
else {
Iwidth = iw / rh;
Iheight = ih / rh;
}
}
Iwidth=Math.round(Iwidth);
Iheight=Math.round(Iheight);
}
function setup(url) {
L_Image = new Image;
L_Image.src=url;
L_ImageSize(L_Image.width, L_Image.height);
}


-- In body of page --
<script language="JavaScript" type="text/JavaScript">
<!--
setup("{BIG_IMAGE}");
alert("Image : "+"{BIG_IMAGE}"+"\nImage dimensions : "+Iwidth+" W x "+Iheight+" H");
-->
</script>
.
.
.
<script language="JavaScript" type="text/JavaScript">
<!--
document.writeln('<img id="Image" src="{BIG_IMAGE}" ALIGN="top" BORDER="0" width="'+Iwidth+'" height="'+Iheight+'">');
-->
</script>

gil davis
10-09-2003, 08:42 AM
The problem is that the browser will start loading an image and then immediately resume processing the web page without waiting for the image to finish. The image properties are not available until the image is loaded. On the second try, the image has finished and has been placed in cache so that the browser can get it quicker. It is a race between loading the image and executing the program statement.

To ensure that you wait until the image is loaded, you can use the image tag's onLoad event or the body onLoad event to get the information you need.

tjdrew
10-09-2003, 09:37 AM
Gil
Many thanks for your insights, as a result I have now resolved the issue with the aid of onLoad in the img tag.