Create a Preloader class in Actionscript 3


/ Published in: ActionScript 3
Save to your folder(s)

A complete example of how we can create a Preloader in actionscript3 to load an external .swf file.

STRUCTURE
------------------
Source Swf
|_ Main.fla
|_ Main.as
|_ Main.swf
Preloader Swf
|_


Copy this code and paste it in your HTML
  1. /*
  2. * main.fla -> main.as
  3. */
  4.  
  5. package
  6. {
  7. import flash.display.MovieClip;
  8. import flash.events.Event;
  9. /**
  10. * ...
  11. * @author Faisal
  12. */
  13. public class Main extends MovieClip
  14. {
  15.  
  16. public function Main()
  17. {
  18.  
  19. if (stage)
  20. {
  21. init();
  22. }
  23. else
  24. {
  25. addEventListener(Event.ADDED_TO_STAGE, init);
  26. }
  27.  
  28. }
  29.  
  30.  
  31. private function init(e:Event = null):void
  32. {
  33. trace("I am main file loaded from Main.fla :)");
  34. }
  35.  
  36. }
  37.  
  38. }
  39.  
  40.  
  41.  
  42. /*
  43. * preloader.fla -> preloader.as
  44. */
  45.  
  46. package
  47. {
  48. import flash.display.Loader;
  49. import flash.display.MovieClip;
  50. import flash.events.Event;
  51. import flash.events.ProgressEvent;
  52. import flash.net.URLRequest;
  53. /**
  54. * ...
  55. * @author Faisal
  56. */
  57. public class Preloader extends MovieClip
  58. {
  59.  
  60. public function Preloader()
  61. {
  62. if (stage)
  63. {
  64. init();
  65. }
  66. else
  67. {
  68. addEventListener(Event.ADDED_TO_STAGE, init);
  69. }
  70.  
  71. }
  72.  
  73. private function init():void
  74. {
  75. var url:URLRequest = new URLRequest("Main.swf");
  76. var myLoader:Loader = new Loader();
  77. myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderComplete);
  78. myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoaderProgress);
  79.  
  80. myLoader.load(url);
  81. }
  82.  
  83. private function onLoaderComplete(e:Event):void
  84. {
  85. trace(e.currentTarget.content);
  86. var a:MovieClip = new MovieClip();
  87. stage.addChild(a);
  88. a.addChild(e.currentTarget.content)
  89. }
  90.  
  91. private function onLoaderProgress(e:ProgressEvent):void
  92. {
  93. var loaded:Number = (e.bytesLoaded / e.bytesTotal) * 100;
  94. trace(loaded);
  95. }
  96.  
  97. }
  98.  
  99. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.