I have a video element and a script that attaches an onplay handler to the video via jQuery:
<video id="vid" />
<!-- ... -->
<script type="text/javascript">
$('#vid').on('play', function () {
$(this).addClass('playing');
});
</script>
According to this answer, users might be able to interact with the video player before the script is loaded. But I need to make sure that my event handler is attached before the onplay event can be fired.
To test this, I added a script right after the video that calls play(). The handler is run on all major browsers except WebKit, which doesn’t play the video at all. Even wrapping the jQuery statement in a $().ready() function still lets the handler be attached before onplay.
Is it guaranteed that my script will never miss any events from the video in HTML5? Does the same apply to all DOM events? What if I add async to the script?
A race condition in that case used to be possible:
However, the spec has been changed to alleviate this problem. Now browsers are supposed to queue firing of events until next event loop run, instead of firing them immediately.
If the script attaching event handlers is an inline script immediately following the
<video>, running without waiting for DOMReady, then race condition won’t happen in compliant browsers.If you use external or async script, wait for DOMReady, use
setTimeoutor synchronous XHR, then you may miss those events, since those things can cause event loop to be processed (although I’m not 100% sure whether network stall allows browsers to process the event loop).I don’t know whether WebKit has been updated to support the safer behavior. If you still have problems, then you can use methods that work even when events are fired instantly:
Use inline event handler:
Create the element programmatically (
document.createElement('video')) with handlers attached before it’s inserted into the document.