告诉是否在Javascript中加载视频

Tell whether video is loaded or not in Javascript

本文关键字:加载 视频 Javascript 是否      更新时间:2023-09-26

我一直在使用侦听器

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

查看它是否大于0,当视频加载或不加载时。这适用于一个非常小的视频,只在谷歌浏览器。它在Firefox中根本不起作用。有什么办法让它工作吗?

我实际上想要等到3个独立的视频加载后再执行一个特定的操作,我该怎么做呢?

试试这个:

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

UPDATE:

正如其他人所提到的,我下面的原始解决方案确实有效,但它可能导致性能问题和行为中的一些不可预测性。

因此我建议听loadeddata事件。阅读更多: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
   }
});

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

下解决方案:

我发现使用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()

要使其成为侦听器,在通常情况下,您需要侦听suspend事件。当下载因任何原因暂停或停止时触发,包括下载已完成。

您还需要在内容已经加载(例如,从缓存)的情况下收听播放

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

在video元素上使用onloadddata事件。它检查视频是否被加载。

当媒体当前播放位置的帧加载完成时触发loadddata事件;通常是第一帧。

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

我有别的办法

    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