Gabriel Gabriel - 10 months ago 158
Javascript Question

The canplay/canplaythrough events for an HTML5 video are not called on Firefox. Why?

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

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

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

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.


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

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

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) {