Lab: SWFObject

Returning a 'success' boolean

When using SWFObject 1.5 and JavaScript to embed a SWF, SWFObject's "so.write" function returned a boolean indicating whether the write was successful. Here's a simple example of what was possible in SWFObject 1.x:

var so = new SWFObject( ... ); 
if(so.write("targetdiv")){ 
  //do something 
} 

Since SWFObject 2.0's dynamic publishing option uses a domready/onload event, it doesn't return a boolean the same way SWFObject 1.x did.  In most cases, this is no big deal. However, some developers rely on the boolean to handle presentation of alternate content or page styling. For instance, a developer may want to load an image or complex markup when the SWF fails to load, but otherwise doesn't want to weigh down the page/load time with the extra code.  A boolean indicating success would help him/her handle their custom DOM manipulation.

So what's a developer to do? Well, since SWFObject 2.0 has an very flexible API, we can 'roll our own' custom embed script that returns a boolean. Here's a relatively simple method I came up with; this function uses SWFObject 1.x-style syntax (which I find convenient), and returns a boolean indicating success.

swfobject.customEmbed = function (swfLoc, id, w, h, version, color){
   if (swfobject.hasFlashPlayerVersion(version)){ 
      var so = swfobject.createSWF({data:swfLoc,width:w,height:h}, {bgcolor:color},id); 
      if(so){ return true; } 
  } 
  return false; 
} 

The custom embed function could be used like this:

var success = swfobject.customEmbed("/lab/_common/sample.swf", "flashcontent", "550", "400", "10", "#FFFFFF");

if(!success){ 
   //embed failed! do something appropriate 
   document.getElementById("flashcontent").innerHTML = "SWFObject was unable to load the SWF!"; 
} 

If a developer wanted to package the whole thing into a domready event, they could do it like this:

swfobject.customEmbed = function (swfLoc, id, w, h, version, color){ 
   if (swfobject.hasFlashPlayerVersion(version)){ 
      var so = swfobject.createSWF({data:swfLoc,width:w,height:h}, {bgcolor:color},id); 
      if(so){ return true; } 
   } 
   return false; 
} 

function loadSWF(){ 
   var success = swfobject.customEmbed("/lab/_common/sample.swf", "flashcontent", "550", "400", "7", "#FFFFFF"); 
   if(!success){ 
      document.getElementById("flashcontent").innerHTML = "SWFObject was unable to load the SWF!"; 
   } 
} 
    
swfobject.addDomLoadEvent(loadSWF);

Here's a working example (tested in IE6, FF2 and Safari 3.1 Windows)