在Javascript中判断视频是否已加载

问题描述 投票:25回答:4

所以,我一直在使用听众

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

在视频加载与否时,查看它是否大于0。这适用于非常小的视频,仅适用于Google Chrome。它根本不适用于Firefox。有关如何使其工作的任何想法?

我本来想等到加载3个单独的视频来采取特定的动作,我该如何解决这个问题?

javascript html5 video loaded
4个回答
36
投票

试试这个:

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

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

在这里阅读:https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState


10
投票

我发现使用setInterval可以主动收听视频的readyState,每隔半秒检查一次,直到它加载为止。

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);
}

如果你不使用ES6,只需用() =>替换function()


4
投票

为了使它成为一个监听器,在正常情况下,你会想要听取暂停事件。当下载因任何原因暂停或停止时触发,包括它已完成。

当内容已经加载时(例如,来自缓存),您还希望收听播放的情况

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");
    }
});

资料来源:https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events


1
投票
var video = document.getElementById("video");
video.onloadeddata = function() {
    // video is loaded
}
© www.soinside.com 2019 - 2024. All rights reserved.