Preloading audio files / events?

I preload all of my assets before starting a JS based application:

assets = [....]; // files $.each(assets,function(){ var r = /\.([^\.]+)$/; var ext = r.exec(this); //get file type if (ext[1] == 'png'){ var tmp = new Image(); } else if (ext[1] == 'mp3'){ var tmp = new Audio(); } tmp.src = this; tmp.onload = function(){ var i = assets.indexOf(this); assets.splice(i,1); if (!assets.length){ console.log('all loaded'); app.build(); } } }); 

This works fine when I only have png in my array, but when I add audio (mp3), a DOM element is created, but it never starts onload , so the application never starts. I tried adding tmp.load() already, but it didn’t make any difference - also I could not find comprehensive information on the Internet. Is it possible that this approach is possible? Can Audio() fire the corresponding event? Thank you

+1
source share
1 answer

You are looking for multimedia events that say you can use, for example. loadeddata .

I would like to dwell on some other points:

  • Characters within the regexp character group do not require escaping.
  • Why not use jQuery to create elements and bind an event handler?

I changed the code a bit:

 $.each(assets, function() { var r = /\.([^.]+)$/, ext = r.exec(this), //get file type tmp = ext[1] === 'png' ? $("<img>") : $("<audio>"), eventName = ext[1] === 'png' ? 'load' : 'loadeddata'; tmp .on(eventName, function() { var i = assets.indexOf(this); assets.splice(i, 1); if (!assets.length){ console.log('all loaded'); app.build(); } }) .attr("src", this); // only set after adding the load callback // to avoid a possible race condition }); 
+2
source

All Articles