0

I am using a Javascript code to detect if a video is loaded.

Once it is loaded I want to add an autoplay attribute to the <video> tag to make it play but I can't find a way to add that attribute. Here is the code I use:

window.addEventListener('load', function() {
    var video = document.querySelector('#bgvid');
    var div = document.getElementById('#bgvid');

    function checkLoad() {
        if (video.readyState === 4) {
            alert('video is loaded')
            video.setAttribute("autoplay")
        } else {
            setTimeout(checkLoad, 100);
        }
    }

    checkLoad();
}, false);

******************* THE SOLUTION ********************

First, thanks DontVoteMeDown for the help.

Proper code should be:

document.getElementById('bgvid').addEventListener('canplaythrough', function() {
    this.play();
    });

2 Answers 2

1

Why not add the attribute to the tag? From the docs:

autoplay: (...) the video will automatically begin to play back as soon as it can do so without stopping to finish loading the data.

So I presume (not sure, indeed) that the video will start playing as soon it loads a part of the video.

Anyway, if you still want to add the attribute, the video tag has some Events, from docs:

  • canplay: Sent when enough data is available that the media can be played, at least for a couple of frames;
  • canplaythrough: Sent when the ready state changes to CAN_PLAY_THROUGH, indicating that the entire media can be played without interruption(...);

So you can use one of those events to set the attribute, e.g:

document.getElementById('bgvid').addEventListener('canplay', function() {
    this.setAttribute("autoplay", "autoplay");
});

With this you can avoid using timeouts, which isn't the best approach.

Sign up to request clarification or add additional context in comments.

3 Comments

I know autoplay is supposed to make video start play only when enough data is buffered, but actually each browser behaves differently, and sometimes video is stuck, this is why I prefer to first load the full video and only then to play it
Your code was good - one thing that needed to change is the setattribute, as it turns, adding autoplay attribute after document is loaded doesn't help. proper solution was to add video.play()
@EyalBinehaker nice, you ended with the perfect solution.
1

with autoplay enabled there is no need to check its load state, the video will simply play when it can, is loaded.

video.autoplay = true;

Look here

1 Comment

Thanks for the help, as it turns, adding autoplay attribute after document is loaded doesn't help. proper solution is video.play().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.