title: Problems preloading audio in Javascript
body: <p>I'm trying to make a cross-device/browser image and audio preloading scheme for a GameAPI I'm working on. An audio file will preload, and issue a callback once it completes.</p>
  
  <p>The problem is, audio will not start to load on slow page loads, but will usually work on the second try, probably because it cached it and knows it exists.</p>
  
  <p>I've narrowed it down to the audio.load() function. Getting rid of it solves the problem, but interestingly, my motorola droid needs that function.</p>
  
  <p>What are some experiences you've had with HTML5 audio preloading?</p>
  
  <p>Here's my code. Yes, I know loading images in a separate function could cause a race condition :)</p>
  
  <pre><code>var resourcesLoading = 0;
  
  function loadImage(imgSrc) {
      //alert("Starting to load an image");
      resourcesLoading++;
  
      var image = new Image();
      image.src = imgSrc;
  
      image.onload = function() {
          //CODE GOES HERE
          //alert("A image has been loaded");
          resourcesLoading--;
          onResourceLoad();
      }
  }
  
  function loadSound(soundSrc) {
      //alert("Starting to load a sound");
      resourcesLoading++;
  
      var loaded = false;
  
      //var soundFile = document.createElement("audio");
      var soundFile = document.createElement("audio");
      console.log(soundFile);
      soundFile.autoplay = false;
      soundFile.preload = false;
  
      var src = document.createElement("source");
      src.src = soundSrc + ".mp3";
      soundFile.appendChild(src);
  
      function onLoad() {
          loaded = true;
  
          soundFile.removeEventListener("canplaythrough", onLoad, true);
          soundFile.removeEventListener("error", onError, true);
  
          //CODE GOES HERE
          //alert("A sound has been loaded");
          resourcesLoading--;
          onResourceLoad();
      }
  
      //Attempt to reload the resource 5 times
      var retrys = 4;
  
      function onError(e) {
          retrys--;
  
          if(retrys &gt; 0) {
              soundFile.load();
          } else {
              loaded = true;
  
              soundFile.removeEventListener("canplaythrough", onLoad, true);
              soundFile.removeEventListener("error", onError, true);
  
              alert("A sound has failed to loaded");
              resourcesLoading--;
              onResourceLoad();
          }
      }
  
      soundFile.addEventListener("canplaythrough", onLoad, true);
      soundFile.addEventListener("error", onError, true);
  }
  
  function onResourceLoad() {
      if(resourcesLoading == 0)
          onLoaded();
  }
  </code></pre>
  
  <p>It's hard to diagnose the problem because it shows no errors and only fails occasionally.</p>