Executing JavaScript When the SWF Has Finished Loading

SWFObject's callback feature enables you to execute JavaScript when the SWF is embedded. However, one gotcha people frequently run into is that the callback executes when the <object> is created, not when the SWF is fully loaded — there is normally a substantial delay between the completion of the <object> creation and the availability of the SWF.

If you need to execute JavaScript when the SWF has finished loading, wrap your code in a timer that polls the SWF's PercentLoaded value and waits until it hits "100" before invoking your code:

function swfLoadEvent(fn){
    //Ensure fn is a valid function
    if(typeof fn !== "function"){ return false; }
    //This timeout ensures we don't try to access PercentLoaded too soon
    var initialTimeout = setTimeout(function (){
        //Ensure Flash Player's PercentLoaded method is available and returns a value
        if(typeof e.ref.PercentLoaded !== "undefined" && e.ref.PercentLoaded()){
            //Set up a timer to periodically check value of PercentLoaded
            var loadCheckInterval = setInterval(function (){
                //Once value == 100 (fully loaded) we can do whatever we want
                if(e.ref.PercentLoaded() === 100){
                    //Execute function
                    //Clear timer
            }, 1500);
    }, 200);

To use this custom swfLoadEvent function, you invoke it via your SWFObject callback:

//This function is invoked by SWFObject once the <object> has been created
var callback = function (e){
    //Only execute if SWFObject embed was successful
    if(!e.success || !e.ref){ return false; }
        //Put your code here
        alert("The SWF has finished loading!");
swfobject.embedSWF("movie.swf", "flashcontent", "550", "400", "9", false, false, false, false, callback);

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!