Table of contents
Animated GIFs need to be fully downloaded before they can be played. This can take a toll on your website's loading speed. You should consider loading your animations as a video instead by using the following HTML markup.
01: <video loop autoplay>
02: <source src="path/to/video.mp4" type="video/mp4" />
03: </video>
By adding the autoplay
and loop
attributes, your video should play immediately and continuously.
These attributes however are not always enough to get your video to autoplay.
Muting your videos
Some modern browsers like chrome will not auto-play your video if it's not muted [↗]. The general rule of many browsers is that a user must opt-in to certain actions before they can happen.
So we will have to adjust our code above by adding the muted
attribute to get it to auto-play.
01: <video loop muted autoplay>
02: <source src="path/to/video.mp4" type="video/mp4" />
03: </video>
play inline on mobile
Again based on the general rule of allowing the user to control actions on their devices, IOS devices will not auto-play videos unless they are set to play inline.
By default on mobile, videos play in fullscreen. If a video is not set to play inline it will not auto-play. Playing inline ensures the video is not opened up in fullscreen.
01: <video loop muted playsinline autoplay>
02: <source src="path/to/video.mp4" type="video/mp4" />
03: </video>
Last resort
Sometimes all the above solutions might not work. In which case we turn to Javascript to get our video to play.
01: <video loop poster="https://via.placeholder.com/200x200.png/000/fff?text=click%20to%20play" onclick="this.play()">
02: <source src="path/to/video.mp4" type="video/mp4" />
03: </video>
In the code above we added a poster
attribute, this points to a URL that generates an image telling the user to click on the video to get it to play.
The onclick
attribute handles the actual playing of the video ie: onclick="this.play()"
.
Here is another article you might like 😊 Javascript: Add days to the current date