Firefox上不会调用HTML5视频的canplay / canplaythrough事件。为什么? [英] The canplay/canplaythrough events for an HTML5 video are not called on Firefox. Why?

查看:668
本文介绍了Firefox上不会调用HTML5视频的canplay / canplaythrough事件。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个用于管理HTML5视频的jQuery插件。我正在尝试捕捉canplay和canplaythrough事件。在Chrome中,该事件被解雇没有问题。在Firefox中,有时会触发它,有时它不会。

I'm building a jQuery plugin for managing HTML5 videos. I'm trying to capture the canplay and canplaythrough events. In Chrome, the event is fired without problem. In Firefox, sometime it's triggered, sometime it's not.

我在这里简化了我的代码:

I'm simplifying my code a little here:

$('#my_video').on('canplay canplaythrough', function(){
    console.log('canplay event fired');
});

我还尝试使用原生javascript .addEventListener()并且它无效。

I also tried with the native javascript .addEventListener() and it's not working.

知道为什么没有在Firefox上调用该事件以及如何修复它?

Any idea why the event is not called on Firefox and how to fix that?

注意:请不要告诉我使用其中一个已经可用的插件,如jplayer和video-js,我知道它们存在并运行良好,但我必须构建一个内部解决方案。

NOTE: Please do not tell me to use one of the already available plugins like jplayer and video-js, I know that they exist and work well, but I have to build an in-house solution.

推荐答案

问题是,您的视频元素在您注册之前已触发 canplaythrough 事件事件处理程序。

The problem is, that your video element has triggered the canplaythrough event before you registered the event handler.

正如您在自己的答案中所指出的,您可以将脚本放在< head> ,但这对您的网页效果不利。

As you pointed out in your own answer, you can put your scripts in the <head>, but this is bad for your page performance.

解决问题的更好方法是检查 readystate 属性并在这种情况下手动执行你的函数:

A better way to fix your problem is to check the readystate attribute and execute your function manually in that case:

var $video = $('video'),
    videoElement = $video[0];

$video.on('canplaythrough', callback);

// If the video is in the cache of the browser,
// the 'canplaythrough' event might have been triggered
// before we registered the event handler.
if (videoElement.readyState > 3) {
  callback();
}

这篇关于Firefox上不会调用HTML5视频的canplay / canplaythrough事件。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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