Yasir Yasir - 1 month ago 9
Javascript Question

Issues with setTimeout interfering with load event handler

I'm attaching a

load
event handler on a
<track>
element. How can I make sure that the handler gets called even if it gets attached after the
<track>
has already loaded?

E.g.

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

Answer

If the event was fired when no listener was attached then the event is lost. Hopefully, the HTMLTrackElement has a readyState property which can be inspected to know the loading state.

Something like this should work, it attaches the handler to handle subsequent load events and if the track is currently loaded it calls the callback right away as well.

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

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