Reputation: 11822
I am preloading all my assets before I start a JS-based application doing:
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 have just png
s in my Array, yet when I add audio (mp3s) the DOM element gets created, yet it never fires an onload
so the app never starts. I tried adding a tmp.load()
already but it didn't make any difference - also I couldn't really find any comprehensive information on the web. Is this approach even possible? Does an Audio()
even fire an appropriate event? Thanks!
Upvotes: 1
Views: 917
Reputation: 154838
You're looking for media events, which says you could use e.g. loadeddata
.
I'd like to address some other points:
I altered your code a little 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
});
Upvotes: 2