video.play() not working: HTML5 autoplay policy
If you have used JavaScript to play video, you may find a strange error which appears on Safari only.
And the following code triggers this error.
We have a video on the bottom, the video starts to play when it is visible in the viewport. Everything looks fine and the example works on both desktop Chrome and Firefox.
But Safari doesn’t play the video. To understand, we have to know more about autoplay policy in browsers
Autoplay policy
Browsers are a customer facing product. Browser vendors always try to make users happy, especially the mobile web user.
Autoplay is disabled to improve user experience and protect their bandwidth.
Users do not expect audio in web page, they need to find out how to turn the auto started music or video. It is annoying.
Video can be large in file size. For mobile users, they do not want to waste mobile data on a video that they are not interested in viewing. Because of this, most popular mobile browsers disable the autoplay feature.
Play triggered without user interaction is autoplay
Clever programmers can always have a workaround. If autoplay is not allowed, how about we call video.play()
after page load?
Sorry, the browser vendors have already taken this into consideration. play function does not work without user interaction. That’s why our example does not work.
Muted video is an exception
Autoplay muted video is allowed on all devices, even it consumes the same amount of user’s bandwidth.
Don’t surprise. Muted video can be used as an animated picture. With nowadays video compression algorithm, MP4 files can be much smaller than GIF. To play an MP4 video, we need HTML5 video tag. In this case, allowing autoplay is doing good for users.
Short summary of autoplay policy
- No limitation on autoplay muted video
- Mobile browsers and desktop Safari do not allow video with audio start automatically