47

So, I've been using a listener on

document.getElementById("video").buffered.length

to see if it's greater than 0 for when a video's loaded or not. This works for a very small video, and only in Google Chrome. It doesn't work in Firefox at all. Any ideas for how to get this to work?

I essentially want to wait till 3 seperate videos are loaded to take a specific action, how do I go about this?

0

6 Answers 6

69

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

6
  • 1
    Which browsers support that property? Commented Dec 30, 2011 at 23:51
  • 1
    @JaredFarrish According to this Wiki, the support is complete (The WebKit column is empty, but I would be surprised if their implementation was behind Mozilla's/Opera's). Commented Dec 31, 2011 at 0:28
  • 1
    @ŠimeVidas how this can be used if there are more than 1 videos. ? thanks
    – user1642018
    Commented Aug 12, 2016 at 7:08
  • 27
    This answer doesnt make sense. This is not really listening for changes. This is only going to run when the page first loads and if it's ready right away it will only work.
    – Omar
    Commented Mar 24, 2017 at 20:50
  • 2
    @Omar You are correct. I can delete my answer when a true solution is posted. Commented Mar 25, 2017 at 14:52
32

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()

5
  • 2
    Great answer! FYI all this is doing is checking a simple property of the video element. It uses very little processing power, so there's really no need to wait a half second between checks. You can change it to 10 milliseconds and catch the video at almost the exact moment it's loaded.
    – Gavin
    Commented Apr 5, 2019 at 6:50
  • 2
    This is badass. Commented Nov 9, 2019 at 18:10
  • 2
    This answer is fantastic but it blocks the main thread and I am trying to display a spinner there... the spinner animation freezes every second.
    – Duck
    Commented May 22, 2020 at 1:26
  • 1
    @DuckDucking you're right. Using setInterval might get the job done but it's far from ideal. I updated my answer with an new and improved solution that shouldn't cause performance issues.
    – Badrush
    Commented May 26, 2020 at 2:00
  • It's 2023 now and the "inferior" solution is the only one that worked for me on Firefox. loadeddata did nothing even though it is listed on MDN as working in all browsers.
    – KevinHJ
    Commented Sep 6, 2023 at 17:58
7

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

3

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
}
2
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – Ethan
    Commented May 24, 2018 at 10:22
  • 1
    Well it didn't take me long to research this hint, and in my case it turned out to be the best solution. <video onloadded="mystuff()"... > allowed me to set up a pause, a wait and then a resume to solve choppy video due to low buffering on a live stream
    – Leo Smith
    Commented Jun 30, 2020 at 2:50
0

It's pretty easy for your script to load AFTER the video, if the video is cached. That can make listening to these events unreliable. I resolved this race condition like so:

(() => {
  const video = $('#video');

  const onVideoLoaded = () => {
    ...
  };

  if (video[0].duration > 0)
    onVideoLoaded();
  else
    video.on('loadedmetadata', onVideoLoaded);
})();

This will at least get you to solid ground - if the video loads, your method will always fire exactly once - whether the video loads before the script, or the script before the video. Attaching to the event naively is going to get you code that mysteriously does nothing on cached visits.

-1

I find other way

    const video = document.querySelector('video');

video.addEventListener('canplaythrough', (event) => {
  console.log('I think I can play through the entire ' +
      'video without ever having to stop to buffer.');
});

source - https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplaythrough_event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.