admin管理员组

文章数量:1287966

Does anyone know why loadedmetadata doesn't consistently fire on chrome. If you take this page and keep refreshing while inspecting the console you will see that only like 1 out 3 times it fires.

js code looks like below

jQuery(function($) {
  $('#myvideo').on('loadedmetadata', function() {
      console.log('loadedmetadata');
  });
});

Does anyone know why loadedmetadata doesn't consistently fire on chrome. If you take this page and keep refreshing while inspecting the console you will see that only like 1 out 3 times it fires.

http://output.jsbin./petefipepa

js code looks like below

jQuery(function($) {
  $('#myvideo').on('loadedmetadata', function() {
      console.log('loadedmetadata');
  });
});
Share Improve this question edited Oct 24, 2015 at 9:24 Mohamed-Yousef 24k3 gold badges21 silver badges28 bronze badges asked Oct 24, 2015 at 9:16 DavidDavid 9,9795 gold badges30 silver badges32 bronze badges 1
  • I dont really know the reason .. but another code works jsbin./cutoholare/1/edit?html,js,output – Mohamed-Yousef Commented Oct 24, 2015 at 9:28
Add a ment  | 

2 Answers 2

Reset to default 7

It may be a little late, but if anyone is still looking for the answer, I found a nice solution.

The "loadedmetadata" listener doesn't fire because the audio has already been loaded when the listener is added.

I'm trying to be more clear. Audios when loaded by the browser have different states (readyState):

  1. HAVE_NOTHING
  2. HAVE_METADATA
  3. HAVE_CURRENT_DATA
  4. HAVE_FUTURE_DATA
  5. HAVE_ENOUGH_DATA

Mozilla Documentation about readyState

When we add the listener

$('#audioOrVideo').on('loadedmetadata', function() {});

We wait for the transition from state 0 to state 1 to occur.

Imagine that an audio is put at the beginning of the page and during the loading of the document it quickly loads. The audio goes from state 0 to a state greater than 0, and then we add the listener.

Our listener will never receive the event because it occurred before the listener was even added.

I propose a solution that has worked for me.

var audioOrVideo = document.getElementById('audioOrVideoElement');
$(document).ready(function() {
        // Attendiamo che venga caricato l'audio
        if (audioOrVideo.readyState > 0) {
            //code
        } else {
            audioOrVideo.on("loadedmetadata", function(_event) {
                //code
            });
        };
    });

The loadedmetadata event is something like the xhr onreadystatechange, it's checked periodically and during the period a certain amount of data has been loaded, it could be the whole package or just the headers.

https://dev.opera./articles/consistent-event-firing-with-html5-video/ You can read more there.

本文标签: javascriptWhy does loadedmetadata not consistently fireStack Overflow