Autoplay video JavaScript
If youre trying to autoplay videos on the web, you might be tempted to reach for the HTML5 autoplay attribute. This sounds exactly like what youre looking for, right? Well, not exactly. Lets talk about why thats probably not what youre looking for and what the better option is. Over the last few years, all major browser vendors have taken steps to aggressively block autoplaying videos on webpages. Safari announced some policy changes in June 2017 and Chrome followed suit shortly after and Firefox after that. In summary: all these browsers will aggressively block videos from autoplaying on webpages. Each browser has slightly different rules around how it makes this decision. Its a huge black box and browsers will not tell you what their exact rules are. The default behavior is block most autoplay attempts. There are however some conditions that make it more likely for autoplay to work:
These conditions only make autoplay more likely, but remember that aside from these conditions, the user can override the browsers default setting on a per-domain basis. This basically means that you can never rely on autoplay actually working. Even if you try to follow the rules above, autoplay is still a finicky beast. One thing to keep in mind (for Chrome at least) is that due to Chromes Media Engagement Index. When you are testing autoplay on your own site it will probably work for you (because you visit your site often and play content, your MEI score is high). But then when new users come to your site, it is likely to fail (because their MEI score is low). As a developer, this is incredibly frustrating and another reason to always avoid the autoplay attribute. Im not suggesting that you avoid autoplaying videos, but I am suggesting that you always avoid the autoplay attribute. There is a better way.
If you look at mux.com youll see that we autoplay a video on the top of the home page. I copied over how we did that and set up a demo here: https://o9s4w.csb.app/. The code is copied below and you can fork it and play around with the Code Sandbox. Notice that were doing a few things here:
|