stageWidth is zero in IE

Posted: 26/02/08

An image of stageWidth is zero in IE

There's a strange bug in SWFs embedded in IE using SWFObject where even after your ADDED_TO_STAGE events have fired, on initialisation both stage.stageWidth and stage.stageHeight are 0. This can cause no end of problems in your app, particularly if you're relying on these two values to measure your UI assets for layout.

The solution isn't a perfect one, but it works nonetheless....

In IE the SWFs stageWidth and stageHeight are initialised at zero, then after a short delay they are updated to the correct values. There are a number of ways you could handle this delay (such as using a timer), but the only certain way of ensuring the values have truely updated before attempting to use them is to listen for the stage RESIZE event. When the SWF is updated with it's correct width and height values (milliseconds after it's initialised), Flash fires the resize event for the stage. You can then assign a callback that then kicks-off the sizing and positioning of the display objects.

When the app reaches the point where it needs to get the stageWidth and stageHeight values, and finds them to be 0, you need to assign

stage.addEventListener( Event.RESIZE, onStageResize )

This will cause an the necessary event callback once IE 'allows' these values to be updated. When the callback is raised, we do a quick sanity check to ensure the stageWidth and stageHeight aren't still zero, and then allow the app to continue with its measurements.

BE CAREFUL though, as in Firefox and other browsers, the RESIZE event probably won't be called, and the width and height will already be correctly set, so you'll want to your app to call onStageResize( null ) straightaway. Remember also to remove the RESIZE event listener after you've has a satisfactory callback, so that you don't keep repeating measuring, drawing and positioning routines.

public function MyConstructor()

{

addEventListener( Event.ADDED_TO_STAGE, onAddedToStage );

}

private function onAddedToStage( e:Event ) :void

if( stage.stageWidth == 0 && stage.stageHeight == 0 )

{

stage.addEventListener( Event.RESIZE, onStageResize );

}

else

{

onStageResize( null );

}

}

private function onStageResize( e:Event) :void

{

if( stage.stageWidth > 0 && stage.stageHeight > 0 )

{

stage.removeEventListener( Event.RESIZE, onStageResize );

//Do stuff

}

}

Keywords for this post: actionscript 3, flash, stage, stageWidth, IE7, resize