Skip to content

Instantly share code, notes, and snippets.

@Karendev
Forked from chris-castillo-dev/lazy-load-bg.js
Created February 14, 2021 01:39
Show Gist options
  • Save Karendev/e3656a7024ec24b39cc0834a37947fc0 to your computer and use it in GitHub Desktop.
Save Karendev/e3656a7024ec24b39cc0834a37947fc0 to your computer and use it in GitHub Desktop.
document.addEventListener("DOMContentLoaded", function() {
var lazyBackgrounds = [].slice.call(document.querySelectorAll(".lazy-bg"));
if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) {
let lazyBackgroundObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
entry.target.classList.add("bg-visible");
lazyBackgroundObserver.unobserve(entry.target);
}
});
});
lazyBackgrounds.forEach(function(lazyBackground) {
lazyBackgroundObserver.observe(lazyBackground);
});
}
});
@Karendev
Copy link
Author

Enqueue script if using WordPress

wp_enqueue_script( 'bg-lazy-loading', '/path-to-js/bg-lazy-loading.js’, array( 'jquery' ), ‘1.0.0’, true );

Add class of .lazy-bg

Forked from Chris Castillo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment