I'm working with an embedded video from a company called Wistia (wistia.com). My goal is to lazyload the video, but there's a dependency that needs to load with the accompanying script. On Click, the script is appended to the head of the page. However, an additional click is needed to play the video.
How do I load the dependency to the head and immediately start playing the video without the additional click?
var xhr = new XMLHttpRequest();
var baseUrl = "https://fast.wistia.com/oembed/?url=";
var accountUrl = encodeURIComponent("https://home.wistia.com/medias/");
var wistiaId = document.querySelector('.wistia_embed').getAttribute('data-wistia-id');
xhr.open('GET', baseUrl + accountUrl + wistiaId + "&format=json&callback=?");
xhr.send(null);
xhr.onreadystatechange = function () {
var DONE = 4;
var OK = 200;
if (xhr.readyState === DONE) {
if (xhr.status === OK)
var data = JSON.parse(xhr.responseText);
var thumb = data.thumbnail_url.split('?')[0];
var wistcont = document.querySelector("#wistia_" + wistiaId);
var wistimg = document.createElement("img");
wistimg.setAttribute("id", 'wistia_preview');
wistimg.setAttribute("src", thumb + "?");
wistimg.classList.add("responsive-img");
wistcont.appendChild(wistimg);
wistimg.addEventListener("click", function () {
(function() {
wistiaEmbedSupport = document.createElement('script');
wistiaEmbedSupport.setAttribute('src', 'https://fast.wistia.com/assets/external/E-v1.js');
WistiaContainers = document.querySelector('.wistia_embed');
WistiaContainers ? document.head.appendChild(wistiaEmbedSupport) : console.log('Nothing to see... ');
})();
wistiaEmbed = Wistia.embed(wistiaId, {
autoPlay: true,
controlsVisibleOnLoad: false
});
}, false);
//console.log(JSON.parse(xhr.responseText));
} else {
//console.log(xhr.status);
}
}
.embed-responsive::before {
padding-top: 56.25%;
display: block;
content: "";
}
*, ::after, ::before {
box-sizing: border-box;
}
.responsive-img{
max-width: 100%;
height: auto;
}
.embed-responsive {
position: relative;
display: block;
width: 100%;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item, .embed-responsive embed, .embed-responsive iframe, .embed-responsive object, .embed-responsive video {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
<div class="cs__page-video">
<div class="embed-responsive">
<div id="wistia_u1p1pze1an" data-wistia-id="u1p1pze1an" class="embed-responsive-item wistia_embed"></div>
</div>
</div>