Skip to content

Instantly share code, notes, and snippets.

@Neoglyph
Created November 27, 2018 09:48
Show Gist options
  • Save Neoglyph/730c8bc5250567a4619b74472f40ee82 to your computer and use it in GitHub Desktop.
Save Neoglyph/730c8bc5250567a4619b74472f40ee82 to your computer and use it in GitHub Desktop.
Lazyload background images
const loadBackgroundImage = (element) => {
if (typeof element.dataset.src === 'undefined') { return }
const src = element.dataset.src
element.style.backgroundImage = `url(${src})`
element.removeAttribute('data-src')
}
const handleIntersection = (entries, observer) => {
for(let i = 0; i < entries.length; ++i) {
loadBackgroundImage(entries[i].target)
}
}
const lazyloadObserver = new IntersectionObserver(handleIntersection)
const targets = document.querySelectorAll('.lazybgload[data-src]')
for(let i = 0; i < targets.length; ++i) {
lazyloadObserver.observe(targets[i])
}
@Neoglyph
Copy link
Author

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