1

I need to have a 10 sec video loop on the hero section of this website but it wont play on initial page load but after I navigate to another route and come back, then the video starts playing. (with autoplay attribute).

I have tried the same video with a 10x smaller file size so it cannot be because of the file size I assume.

I also tried loading the video with XMLHttpRequest like this:

const video = document.createElement('video')
            var req = new XMLHttpRequest();
            req.open('GET', 'video.mp4', true);
            req.responseType = 'blob';

            req.onload = function() {
                if (this.status === 200) {
                    var videoBlob = this.response;
                    var vid = URL.createObjectURL(videoBlob);

                    video.src = vid;
                    const parentEl = document.querySelector('.video');
                    parentEl.appendChild(video);
                }
            }
            req.onerror = function() {
            // Error
            }

            req.send();

And I also tried like this:

const video = document.createElement('video');
            video.src = '/intro_online.mp4';
            console.log(video)

            video.addEventListener('canplaythrough', (e) => {
                video.autoplay = true;
                video.preload = "auto"

                const parentEl = document.querySelector('.video');
                parentEl.appendChild(video);
            });

But none of these solves the problem. What could I try to get over this problem?

Nicolas
  • 434
  • 1
  • 3
  • 13
  • 2
    A quick search shows [this answer](https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use), can you check to see if this solves your issue? – PedroSantana Mar 06 '23 at 14:18
  • can you try giving the video `autoplay` property before your give it a `src`? – Arik Mar 06 '23 at 14:19

1 Answers1

1

The muted property seems be required in order to play it. I added this to the dom:

<video class="video" autoplay muted loop preload="auto">
    <source src="intro_online.mp4" type="video/mp4">
</video>

I didn't have the muted attribute in my previous attemps but now it works.

Nicolas
  • 434
  • 1
  • 3
  • 13