Skip to content

Instantly share code, notes, and snippets.

@chris-castillo-dev
Created February 13, 2021 21:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save chris-castillo-dev/a2e118f5650aeaf55a814d18d5700a5b to your computer and use it in GitHub Desktop.
Save chris-castillo-dev/a2e118f5650aeaf55a814d18d5700a5b 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);
});
}
});
@ROGMARQ14
Copy link

Hey Chris so, this would go inside the function.php file?

@chris-castillo-dev
Copy link
Author

Hey Chris so, this would go inside the function.php file?

Well, you need to load this script on the site somehow either:

  1. Save the script as a .js file on your site somewhere and then enqueue it via your functions.php file, OR
  2. Use a plugin like Code Snippets to inject the JS code to every page.

Personally, I prefer enqueuing the file using the functions.php file because I like to limit the use of 3rd party plugins.

@webwizz
Copy link

webwizz commented May 7, 2021

Hi Chris,

I was trying this out using Code Snippets plugin and it reported an error on line 2:

The code snippet you are trying to save produced a fatal error on line 2:

syntax error, unexpected 'var' (T_VAR)

I'm using Elementor and lazyloading background images is the last thing I need to sort out.

@chris-castillo-dev
Copy link
Author

Hi Chris,

I was trying this out using Code Snippets plugin and it reported an error on line 2:

The code snippet you are trying to save produced a fatal error on line 2:

syntax error, unexpected 'var' (T_VAR)

I'm using Elementor and lazyloading background images is the last thing I need to sort out.

If you got the enqueue line of code from the article on my website, you need to watch out with the quote symbols ( " and ' ) when you copy and paste. Just delete and type those characters in again. Something about the way the code renders on the site makes the encoding of those characters incorrect.

Hope this helps.

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