Issues with setTimeout interfering with the load event handler

I am attaching an event handler loadto an element <track>. How can I make sure that the handler is called even if it connects after it is <track>already loaded?

eg.

track.addEventListener('load', function () {
    //this should get called even if the track has already loaded
});
+4
source share
4 answers

If the event was fired when the listener was not attached, the event will be lost. We hope that it HTMLTrackElementhas a property readyStatethat can be checked to find out the status of the download.

- , , , .

function whenLoaded(track, callback) {
    const LOADED = 2;

    track.addEventListener('load', callback);
    if (track.readyState === LOADED) callback();
}
+1

, . foo.

function foo(div) {
  div.addEventListener('click', function() {
    console.log('this loads');
  });
};


var div = document.getElementById('main');
  
setTimeout(function() {
  foo(div);
}, 1000);
#main {
  background-color: red;
  width: 100px;
  height: 100px;
}
<div id="main"></div>
Hide result
0

. load , , default <track>.

, src <track> <track> <video>?

<track> <video>. src foo, load track <video>, <track> <video>, src , foo

window.onload = function() {

  // append next `track` element to `video` in 1 seconds
  setTimeout(function() {
    // pass `src`, `label` to set at `track` element
    addTrack("/path/to/resource2", "track 1") 
  }, 1000);

  function foo(track, src) {  
    track.addEventListener("load", function() {
      console.log("this loads");
    });
    video.appendChild(track);
    track.src = src;
  };

  function addTrack(src, tracklabel) {
    var track = document.createElement("track");
    track.kind = "captions";
    track.srclang = "en";
    track.label = tracklabel;
    // set `default` attribute at `track` element
    track.setAttribute("default", "default");
    // pass `track` element, `src` to set at `track` to `foo`
    foo(track, src);
  }

  addTrack("/path/to/resource1", "track 1");

}
0

:

, .

. , , , . , .. body, , .

, .

, event.target , . , , , , .

. .

0

Source: https://habr.com/ru/post/1657826/


All Articles