Fix HTML Video Autoplay Not Working

To optimise pages on this blog I recently replaced the animated GIFs with auto-playing videos. It required a couple tries to get it right, so here’s how it works.

The video below won’t autoplay.

<video autoplay>
    <source src="video.mp4" type="video/mp4" />
</video>

To fix this we add the muted attribute, this will disable the audio, making the video less intrusive.

<video autoplay muted>
    <source src="video.mp4" type="video/mp4" />
</video>

However the video above still won’t autoplay on iOS Safari, Safari requires us to add the playsinline attribute.

<video autoplay muted playsinline>
    <source src="video.mp4" type="video/mp4" />
</video>

We can try to hack around these autoplay limitations with some JavaScript, but that will only work if the JavaScript is run as a result of a user action.

The code below won’t work, it will throw a warning in the developer console.

document.querySelector('video').play();

The play action below will work because the code runs as a result of a user action.

<button>Play</button>

<script>
    document.querySelector('button').addEventListener('click', () => {
        document.querySelector('video').play();
    });
</script>

Press to play the first video on the page.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

More articles More articles