I'm embedding YouTube videos on product pages using a lazy loading script to speed up the page load when videos are embedded. Here's the lazy load script that is in the header.php of the site:
<script type="text/javascript">
/**
Defer parsing of Javascript for any YouTube videos found on a given page.
Relies on using YouTube iframe embed and changing src= to data-src=
Source: https://scottdeluzio.com/defer-parsing-javascript-youtube-videos/
**/
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
</script>
Here's the youtube embed iframe code:
<iframe width="319" height="179" data-src="//www.youtube.com/embed/SKT9G8_hB4E" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Here's the page the video is embedded on:
https://www.intechrahealth.com/product/fenfast-375/
However, when I load the page on any smartphone device and scroll to a point where the video is out of the viewport, and then I scroll back to see the video, a blank spot exists where the video used to be. I can get the video to reappear when I reload the page, but scrolling again makes it disappear.
I've tried removing the "allow=" parameters, but that doesn't fix it. I've also removed the lazy load code and changed "data-src" back to "src", and the videos work normal, but the overall page speed then becomes 15 seconds or so. I need the lazy load code to speed up the page load when videos are present.
Is this the lazy load code's fault? Or is it something else?