Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 pngs 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're looking for media events, which says you could use e.g. loadeddata.

I'd like to address some other points:

  • Characters inside a regexp character group don't need escaping.
  • Why not use jQuery for creating the elements and binding the event handler?

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
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...