最后加载视频元素 [英] Load the video element last

查看:20
本文介绍了最后加载视频元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面顶部有一个视频元素,我想知道在加载其余 DOM 之后是否有任何方法可以加载它?我希望视频最后加载.

I've got a video element at the top of my page, I was wondering if theres any way to load it after the rest of the DOM has been loaded? I want the video to load last.

推荐答案

这似乎可以满足您的需求.在我的示例中,我只包含了一个 mp4 源,但您可以根据您支持的浏览器为 WebM 和 Ogg 添加其他源.您可以简单地填充所有三个属性,或使用 canPlayType 测试来确定最适合用户浏览器的属性.

This seems to do what you want. In my sample I have only included an mp4 source, but you could add others for WebM and Ogg depending on what browsers you are supporting. You can simply populate all three attributes, or use the canPlayType test to determine the best for the users browser.

视频元素默认为自动播放(但您可以从 <video...> 标签中删除该属性并直接从脚本控制它.它也默认为 preload="auto" 让浏览器控制预加载多少,如果它不是最适合您的场景(并且不同的浏览器有非常不同的行为),您可能需要再次关闭它

The video element defaults to autoplay (but you can remove that attribute from the <video...> tag and control it directly from the script. It also defaults to preload="auto" to let the browser control how much to preload, again you might want to turn that off if it's not optimal for your scenario (and different browsers have very different behaviors)

您可能还想隐藏视频元素,直到您准备好加载内容为止(尽管这会使页面稍微晃动并且对用户来说可能看起来很奇怪)

You might also want to hide the video element until you are ready to load content (though that will jiggle the page around a bit and might look weird for the user)

<!DOCTYPE html>
<html>
<head>
<title>Initialize video when doc is ready</title>

<script>
document.onreadystatechange = function () {
  console.log("readyState = " + document.readyState);
  if (document.readyState == "interactive") { // can also wait for "complete" here
    init();
  }
}
function init() {
    console.log("load the source for the video element")
    vid = document.getElementById("video")
    // can use the vid.canPlayType test to only load supported video
    // or have tags for MP4, WebM and Ogg to cover your bases
    vidMP4 = document.getElementById("videoMP4")
    vidMP4.setAttribute("src","video.mp4")
//  vid.play();
}
</script>

</head>
<body>

<p>Something before the video</p>
<video id="video" controls autoplay preload="auto" width=480 height=320>
<source id="videoMP4"></source></video>
<p>Something after the video</p>

</body>
</html>

这篇关于最后加载视频元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆