SWFObject and Ajax (xmlhttprequest)

Here's a common scenario: A developer has two pages: a pure HTML page and a page that contains a SWF. The developer's goal is to use ajax to load the SWF page into the HTML page. Can it be done? Yes, but there are certain restrictions to be aware of, most notably that any content loaded via ajax will not include JavaScript functionality.

Simply put, if you want to make your life easier, use static publishing for your SWF content, ensuring your SWF is embedded using HTML markup and not using JavaScript. Then your ajax (xmlhttprequest) script can simply copy the markup over to the new HTML page. Be sure to use request.responseText in your xmlhttprequest code.

Demo: ajax page, which loads this HTML page containing a SWF.

If you want to push the boundaries a little more, you can use xmlhttprequest to load data about a SWF from an external XML file (including any variables that need to be passed into the SWF using flashvars).

Steps:

  1. Create the page you'd like to load a SWF into
  2. Create the SWF
  3. Create an XML file containing the information needed for the SWF, including any optional parameters you'd like to pass via FlashVars. This includes the SWF file path, width, height, minimum version of Flash Player, etc.
  4. Add an xmlhttprequest to the requesting page. The xmlhttprequest will load the swfData.xml file, then we use a little bit of JavaScript to extract the data.
  5. When the data has been extracted, it's used to populate an instance of SWFObject, which is then used to write the SWF to the page.

Demo: Loading external data. source FLA.

Questions or Comments?

If you have questions or would like to point out an error, please post your remarks in the SWFObject Google Group. Thanks!