Categories
JavaScript Answers

How to Check if a HTML5 Video is Ready with JavaScript?

Spread the love

To check if a HTML5 video is ready with JavaScript, we can listen to the canplay event.

If it’s emitted, then the video is ready.

For instance, if we have:

<video src='https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'></video>

Then we can listen for the canplay event by writing:

const video = document.querySelector('video')
video.addEventListener('canplay', () => {
  console.log('ready')
})

We select the video element with document.querySelector.

Then we call addEventListener with 'canplay' to listen to the canplay event.

The 2nd argument is the event handler for the canplay event, which runs when the video is ready to be played.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.