SoundManager 2: SM2_DEFER Example

This is an example of manually starting SoundManager 2. If you want to pre-load the SM2 script up front and have its onready() events etc. fire much later without delay, this approach makes sense. Otherwise, it's better to lazy-load or simply load SM2 normally as an external script without deferring.

How it works

By default, SM2 will call its own SoundManager() constructor inline and will try to initialize ASAP. This page defines a global boolean - window.SM2_DEFER = true; - before loading soundmanager2.js, preventing the constructor from being called.

Some time later, you must call soundManager = new SoundManager(); manually and set things like soundManager.url etc. Finally, you may then call soundManager.beginDelayedInit() to kick off the initialization process. SM2 should then start as usual.

Example code

<script type="text/javascript">

/*
 * Firstly, define SM2_DEFER and set it to true *before* we load soundmanager2.js.
 * This prevents the SoundManager() constructor from being called immediately.
 * SM2_DEFER should be assigned within the global scope.
*/

window.SM2_DEFER = true;

</script>

<!-- Now, load soundmanager2.js as we normally would. -->
<script type="text/javascript" src="../../script/soundmanager2.js"></script>

<!-- "Some time later", window.onload() may have fired and you now want to start SM2, etc... -->
<script type="text/javascript">

// for example purposes, we'll wait until window.onload before starting things.
window.onload = function() {

  /*
   * Now that the SM2 constructor is defined, you can call the constructor,
   * set the options and "kick-start" SM2's init process, and it should work as normal.
   * WARNING: Do not call beginDelayedInit() before "DOM ready", or things will fail.
  */

  // construct the instance (must be named soundManager, and scoped globally)
  window.soundManager = new SoundManager();

  // assign flash url, flashVersion and other SM2 options as usual
  soundManager.setup({
    // path to directory containing SM2 SWF
    url: '/path/to/swfs/',
    flashVersion: 9
    // etc...
  });

  // finally, kick-start the init process.
  // (old IE etc. may miss domloaded/ready/window.load if they've already fired.)
  soundManager.beginDelayedInit();

}

</script>