Skip to content

Instantly share code, notes, and snippets.

@Thomasorus
Last active December 16, 2020 20:15
Show Gist options
  • Save Thomasorus/f8c524fbe71e554e9bbe41ab6cb8d740 to your computer and use it in GitHub Desktop.
Save Thomasorus/f8c524fbe71e554e9bbe41ab6cb8d740 to your computer and use it in GitHub Desktop.
<-- Put this script AFTER your footer -->
<script>
//Wait for the dom to be loaded
document.addEventListener("DOMContentLoaded", function() {
//Recover an array of all video elements with the "lazy" class on them.
var lazyVideos = [].slice.call(document.querySelectorAll("video.lazy"));
//Check if the browser supports intersection observer
if ("IntersectionObserver" in window) {
var lazyVideoObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(video) {
if (video.isIntersecting) {
for (var source in video.target.children) {
var videoSource = video.target.children[source];
if (typeof videoSource.tagName === "string" && videoSource.tagName === "SOURCE") {
// The original markup had the src empty and a data-src with the url of the video.
// We fill the empty src attribute with the datasrc one.
videoSource.src = videoSource.dataset.src;
}
}
video.target.load();
video.target.classList.remove("lazy");
lazyVideoObserver.unobserve(video.target);
}
});
});
lazyVideos.forEach(function(lazyVideo) {
lazyVideoObserver.observe(lazyVideo);
});
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment