我使用以下代码来检查用户是在桌面上还是在移动设备上,如果在桌面上则填充了视频源的 src=""
属性。一切都很好。填充 src 属性后,我想在显示视频之前检查视频是否已加载。有办法做到这一点吗?
谢谢!
JS
//video
if($.browser.mobile)
{
console.log("is mobile")
// it is mobile browser
}
else
{
console.log("is desktop")
// no mobile browser
var sources = document.querySelectorAll('video#patient-video source');
// Define the video object this source is contained inside
var video = document.querySelector('video#patient-video');
for(var i = 0; i<sources.length;i++) {
sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
}
// If for some reason we do want to load the video after, for desktop as opposed to mobile (I'd imagine), use videojs API to load
video.load();
video.muted= "muted";
$(".main-area--cris-pro").addClass("loaded")
}
要检查它是否是移动浏览器,我使用插件:
detectmobilebrowser.js
我的 HTML 如下:
<video id="patient-video" width="100%" preload="none" poster="../../assets/img/patient-home-1600.jpg" autoplay loop>
<source data-src="../../assets/video/patient-home-video-comp.mp4" src="" type="video/mp4">
<source data-src="../../assets/video/patient-home-video-comp.webm" src="" type="video/webm">
<source data-src="../../assets/video/patient-home-video-comp.ogv" src="" type="video/ogg">
</video>
最佳答案
Use
canplaythrough
event.
当用户代理可以播放媒体时,会触发 canplaythrough
事件,并估计已加载足够的数据来播放媒体直至结束,而无需停止进一步缓冲内容。
var sources = document.querySelectorAll('video#patient-video source');
var video = document.querySelector('video#patient-video');
for (var i = 0; i < sources.length; i++) {
sources[i].setAttribute('src', sources[i].getAttribute('data-src'));
}
video.muted = true;//Set boolean value
video.addEventListener('canplaythrough', function() {
alert('Video Loaded!');
video.muted = false;
$(".main-area--cris-pro").addClass("loaded");
});
关于javascript - 检查填充 src 后视频何时开始播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37542165/