Created
November 27, 2018 09:48
-
-
Save Neoglyph/730c8bc5250567a4619b74472f40ee82 to your computer and use it in GitHub Desktop.
Lazyload background images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/w3c/IntersectionObserver/tree/master/polyfill