Tuesday 27 September 2011

How To Import Scripts and Preload Images

Importing Scripts

WHY?

You might ask the question 'whats the need?' as the conventional way of adding the script into the head of the HTML page is the same principle.
The Main reason is that it gives you the flexibility to add scripts which are necessary for a class to function correctly, for example extends classes.

Another reason is that it save you time adding scripts which are essential to the framework.

WHEN?

You import your script before the stage is initialised so all your scripts are ready to access each other.

HOW?

You ensure the JS3  script is added to the HTML page and then you call the 'import' function.

IMPORT("js/com/component/display/MovieClip");

Provide it with the url to the js file but don't put the extension ('.js').

Preload Images


WHY?

When using Javascript to dynamically build components it will take time to see images for the first time as it needs to load. So the embed feature lets you preload these images before stage is initialised.

HOW?


Call the embed function and pass in the url and the second parameter is the name of the asset, this allows you to reference it in the code.


Embed("images/bg.jpg","Background");

To access it you need to get it from the styleManager, so ensure you have waited till the styleManager has loaded then call the following function.

listening for the styleManager:
styleManager.addEventListener(Event.EMBEDS_LOADED,onloadedStyle)

accessing assets:
styleManager.getAssetByName("Background")



Full Code:

IMPORT("js/com/component/display/MovieClip");


Embed("images/bg.jpg","Background");
Embed("images/loader.png","loader");




(function(window) {


var dis;


stage.addEventListener(Event.ADDED_TO_STAGE,init);
function init()
{

stage.removeEventListener(Event.ADDED_TO_STAGE,init);
stage.addEventListener(Event.RESIZE,resize);

styleManager.addEventListener(Event.EMBEDS_LOADED,onloadedStyle);


}
function onloadedStyle()
{


 dis =new DisplayObject();
dis.background(styleManager.getAssetByName("Background"));
dis.setWidth(300);
dis.setHeight(300);
addChild(dis);


}