How to create a lightweight Flash/SWF library accessible from HTML?

Imagine a situation when you need a Flash functionality in a HTML-based Web application (for example to do a cross domain client-based Ajax request).

Your ActionScript methods can be exposed via flash.external.ExternalInterface class, but a Flex MXML-based application inherits mx.core.Application with all dependencies by default, resulting in a 250 kB SWF file. If you disable debugging info then you can reduce the file size to 150 kB at minimum, but it’s still an overkill to load it in a production application.

The solution is to create an ActionScript-based Flex application instead of MXML-based. Instead of inheriting from Application class it uses a flex.display.Sprite class, which is a basic display-list building block and doesn’t depend on Flex classes, effectively reducing SWF size to tiny 1-2 kB. As the project’s default ActionScript class is executed by default once SWF file is loaded into the browser, it permits registering ExternalInterface callbacks making communication between the browser and SWF library possible.

Here is a basic library ActionScript code:

package {
  import flash.display.Sprite;
  import flash.external.ExternalInterface

  public class Library extends Sprite {

    public function Library() {
      ExternalInterface.addCallback("load", function() {
        ExternalInterface.call("alert", "Hello from SWF library!");
      });
    }
  }
}

Leave a Reply