I recently worked on a site which called for two separate Flash elements to begin their actions simultaneously. Our extremely talented Flash developer couldn’t accomplish this using only the Flash, as they were two completely separate files. Enter Flash’s ExternalInterface. This new (to versions 8 and above) object allows for easier-than-ever coordination between JavaScript and Flash. After our Flash guy implemented it and added some functions for me to reference, I was able to make calls to each file and tell them to start at the same time when they were ready.
The Code
First you’ll have to set up your Flash with two functions, one which will return the “ready state” of the element (just return true when you have loaded sufficiently), and another which will start the action. Then you just have to reference the functions in the following code:
// Given an array of flash element references,
// these functions will ensure they are ready,
// then launch them more or less simultaneously
var flashLoader = flashLoader ? flashLoader : {
flash: new Array(),
checkInterval: 1000,
// Get references to flash elements
init: function(elms) {
for (var i = 0; i < elms.length; i++) {
flashLoader.flash[i] = document.getElementById(elms[i]);
}
flashLoader.checkReady();
},
// Make sure they are both ready
checkReady: function() {
// Bail if an element is not ready
for (var i = 0; i < flashLoader.flash.length; i++) {
if (!flashLoader.flash[i].ready || !flashLoader.flash[i].ready()) {
setTimeout(flashLoader.checkReady,flashLoader.checkInterval);
return false
}
}
// If we got this far, launch the elements!
flashLoader.startThem();
},
// Start the flash elements
startThem: function() {
for (var i = 0; i < flashLoader.flash.length; i++) {
flashLoader.flash[i].commence();
}
}
}
// Load the init without screwing anything up
loadLoader = function () {
flashLoader.init( ['yourFlash1', 'yourFlash2'] );
}
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = loadLoader;
} else {
window.onload = function() {
oldonload();
loadLoader();
}
}
Notice the two Flash function calls:
if (!flashLoader.flash[i].ready || !flashLoader.flash[i].ready()) {
…and:
flashLoader.flash[i].commence();
In some cases you don’t have to perform the ready check, because calling the function on load of the page means it waits until after the Flash is completely loaded. But in other browsers (Safari), the JavaScript is executed earlier, and as such needs the ready check.
