Tell whether video is loaded or not in Javascript

纵然是瞬间 提交于 2019-12-29 03:19:27

问题


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?


回答1:


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




回答2:


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




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/8685038/tell-whether-video-is-loaded-or-not-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!