Yasir Yasir - 1 year ago 69
Javascript Question

Issues with setTimeout interfering with load event handler

I'm attaching a

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


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

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download