I'm adding a video background to my site, that will autoplay when the page loads. The autoplay is intermittent at the moment, and may be affected by ajax calls elsewhere on the page.
When the video doesn't autoplay, i get the following error:
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
function addVideoBackground() {
// SWITCH WHICH VIDEO //
const urlPath = window.location.pathname;
let videoSrc;
switch (urlPath) {
case "/pages/home-recognition":
videoSrc = "https://player.vimeo.com/external/574413787.hd.mp4?s=717309f70fd17c0204187701b2316787944a1fce&profile_id=174";
break;
default:
videoSrc = "https://player.vimeo.com/external/574413787.hd.mp4?s=717309f70fd17c0204187701b2316787944a1fce&profile_id=174";
}
// DECLARE VARIABLES //
const body = document.querySelector('header');
//CREATE BASIC ELEMS //
const videoHolder = document.createElement('div');
const videoOuter = document.createElement('div');
const videoElem = document.createElement('video');
const source = document.createElement('source');
// APPLY ATTRIBUTES
$(videoHolder).addClass("videoHolder");
$(videoOuter).addClass("videoOuter");
$(videoElem).attr({ autoplay: "true", muted: "true", loop: "true", id: "videoBackground" });
$(source).attr({ src: videoSrc, type: "video/mp4" });
// PUT IT ALL ON SITE //
videoElem.appendChild(source);
videoOuter.appendChild(videoElem);
videoHolder.appendChild(videoOuter);
body.appendChild(videoHolder);
}
window.addEventListener('load', async () => {
addVideoBackground()
let video = document.querySelector('video[muted][autoplay]');
try {
await video.play();
} catch (err) {
video.controls = true;
}
});