Tell whether video is loaded or not in Javascript

Use onloadeddata event on the video element. It checks whether the video is loaded or not. See this reference for more information.

The loadeddata event is fired when the frame at the current playback position of the media has finished loading; often the first frame.

var video = document.getElementById("video");
video.onloadeddata = function() {
    // video is loaded
}

Try this:

var video = document.getElementById("video-id-name");

if ( video.readyState === 4 ) {
    // it's loaded
}

Read here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState


UPDATE:

As others have mentioned, my original solution below does work but it can lead to performance issues and some unpredictability in its behaviour.

Therefore I recommend listening to the loadeddata event. Read more here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loadeddata_event

const videoElement = document.getElementById("my_video");

videoElement.addEventListener('loadeddata', (e) => {
   //Video should now be loaded but we can add a second check

   if(videoElement.readyState >= 3){
       //your code goes here
   }

});

==================================

INFERIOR SOLUTION:

I find using setInterval works for actively listening to when the readyState of the video changes by checking every half-second until it loads in.

checkforVideo();

function checkforVideo() {
    //Every 500ms, check if the video element has loaded
    var b = setInterval(()=>{
        if(VideoElement.readyState >= 3){
            //This block of code is triggered when the video is loaded

            //your code goes here

            //stop checking every half second
            clearInterval(b);

        }                   
    },500);
}

If you're not using ES6 just replace () => with function()


To make this into a listener, under normal circumstances, you'll want to listen to the suspend event. It's triggered when download is paused or stopped for any reason, including it's finished.

You'll also want to listen to playing for the cases when the content is already loaded (like, from cache)

video.addEventListener("playing", function() {
    console.log("[Playing] loading of video");
    if ( video.readyState == 4 ) {
        console.log("[Finished] loading of video");
    }
});
video.addEventListener("suspend", function(e) {
    console.log("[Suspended] loading of video");
    if ( video.readyState == 4 ) {
        console.log("[Finished] loading of video");
    }
});

Source: https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events