SoundManager 2: Lazy Loading Example

This is an example of dynamically loading SoundManager 2 using JS, after window.onload() has fired.

How it works

This page waits until window.onload(), delays 1 second and loads soundmanager2.js, which should then start up.

Behaviour note: SM2 will not automatically start if it is loaded at or after the DOMContentLoaded event has fired, which may be common with most JS loaders.

However, SM2 will try to start once soundManager.setup() is called and a url attribute has been provided.

If you want to ensure that SM2 starts after setup, you can call soundManager.beginDelayedInit() - this should be safe to call after DOMContentLoaded has fired.

Pseudo-code Example

Once SM2 has been dymamically loaded, you can call its setup() method. Passing a url attribute will trigger the initialization process.

loadJS('soundmanager2.js', function() {
  soundManager.setup({
    url: '/path/to/swfs/',
    onready: function() {
      // good to go!
      // soundManager.createSound(...), etc.
    }
  });
});

Live Example

SoundManager 2 status: Waiting for window.onload()...

/**
 * Dynamic script loading helper (example)
 * Normalizes good browser onload() vs. IE readyState weirdness
 */

function loadScript(sURL, onLoad) {

  function loadScriptHandler() {
    var rs = this.readyState;
    if (rs == 'loaded' || rs == 'complete') {
      this.onreadystatechange = null;
      this.onload = null;
      if (onLoad) {
        onLoad();
      }
    }
  }

  function scriptOnload() {
    this.onreadystatechange = null;
    this.onload = null;
    window.setTimeout(onLoad,20);
  }

  var oS = document.createElement('script');
  oS.type = 'text/javascript';
  if (onLoad) {
    oS.onreadystatechange = loadScriptHandler;
    oS.onload = scriptOnload;
  }
  oS.src = sURL;
  document.getElementsByTagName('head')[0].appendChild(oS);

}

// Wait for window load, then load soundmanager2.js, let it start and play a test sound

window.onload = function() {

  msg('Window loaded, waiting 1 second...');

  setTimeout(function() {

    msg('Loading soundmanager2.js...');

    loadScript('../../script/soundmanager2.js', function() {

      // SM2 script has loaded

      window.setTimeout(function() {
        msg('soundmanager2.js loaded, delaying before setup()...');
      }, 500);

      window.setTimeout(function() {

        soundManager.setup({
          url: '../../swf/',
          onready: function() {
            soundManager.createSound({
              id: 'foo',
              url: '../_mp3/mouseover.mp3'
            }).play();
            msg('Started OK');
          },
          ontimeout: function() {
            msg('Loaded OK, but unable to start: unsupported/flash blocked, etc.');
          }
        });

        // ensure start-up in case document.readyState and/or DOMContentLoaded are unavailable
        soundManager.beginDelayedInit();

      }, 1000);

    });

  }, 1000);

}

Handling flash blockers

It's good to let users see the flash component of SM2, so those with flash blockers can unblock it and allow SM2 to start. For more info on this, see the Flashblock example.

Preventing auto-init using SM2_DEFER

If you want to completely defer the normal start-up of SM2 and call the SoundManager() constructor yourself, you can declare an SM2_DEFER global and set it to true. See the SM2_DEFER example for details.

Disabling debug output

SoundManager 2 will write to a debug <div> element or a javascript console if available, by default. To disable it, simply set the relevant property to false:

soundManager.setup({ debugMode: false });

To see related configuration code, refer to the source of this page which basically does all of the above "for real."

Troubleshooting

If SM2 is failing to start and throwing errors due to flash security, timeouts or other issues, check out the troubleshooting tool which can help you fix things.

No-debug, compressed version of soundmanager2.js

You can also use the "minified" (60% smaller) version of SM2, which has debug output and comments removed for you: soundmanager2-nodebug-jsmin.js. If you can, serve this with gzip compression for even greater bandwidth savings!