Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@ROGMARQ14 ROGMARQ14 commented Apr 28, 2021

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

@chris-castillo-dev

This comment has been minimized.

Copy link
Owner Author

@chris-castillo-dev chris-castillo-dev commented Apr 28, 2021

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

This comment has been minimized.

Copy link

@webwizz 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

This comment has been minimized.

Copy link
Owner Author

@chris-castillo-dev chris-castillo-dev 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.

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