I'm trying to load multiple versions of the same video on a page. The script runs after page load, but I have to loop through the sources to check if they have been added to the DOM already (otherwise they download the same file multiple times). If that source already exists, the other duplicates of the video must wait until the first version is downloaded, via an eventListener, before loading the duplicate source and using that cached version of the first video to populate the duplicates (so that they don't download multiple times).
It seems to work fine when I test it in the Chrome network tab, the sources are only downloaded once, but when I look at the Lighthouse diagnostics it is telling me that the js execution time needs to be reduced. Is this because of the looping?
I also keep running into the issue of PageSpeed Insights giving me the message: "Oops! Something went wrong. PageSpeed Insights encountered a problem collecting the lab data."
What am I doing wrong here?
var i = 1,
sourceID,
arraySRC = [];
document.querySelectorAll("video source").forEach(function(source, sourceIndex) {
if (source.hasAttribute("data-small-src") && source.getAttribute("data-small-src") != "") {
source.id = "vidsource-" + i;
sourceID = "vidsource-" + i;
var src = source.getAttribute("data-small-src"),
sourceLoading = false,
firstMatchID;
// loop through array to see if source value already exists
arraySRC.forEach(function(itemSRC, arrayIndex) {
// if source value already exists in array
if (itemSRC.split(",")[1] == src) {
sourceLoading = true;
firstMatchID = itemSRC.split(",")[0]
return
}
});
if (sourceLoading == false) {
const node = document.createElement("source");
source.parentElement.appendChild(node);
node.setAttribute("src", src);
} else {
document.querySelector("#" + firstMatchID).addEventListener('loadeddata', function() {
const node = document.createElement("source");
source.parentElement.appendChild(node);
node.setAttribute("src", src);
}, false);
}
// add source to array
arraySRC.push(sourceID + "," + src);
i = i + 1;
}
});
(I have left out the load event for the script since I am using a Barba.js hook)