Last active
October 20, 2020 09:31
-
-
Save xPaw/a6c933d942d6a782ce057128ab8360fe to your computer and use it in GitHub Desktop.
Lazy load elements when they appear in view using IntersectionObserver
This file contains 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
let observer; | |
function LazyLoad( element, callback ) | |
{ | |
if( !( 'IntersectionObserver' in window ) ) | |
{ | |
callback(); | |
return; | |
} | |
if( !observer ) | |
{ | |
observer = new window.IntersectionObserver( entries => | |
{ | |
entries.forEach( entry => | |
{ | |
if( entry.isIntersecting ) | |
{ | |
observer.unobserve( entry.target ); | |
entry.target.dispatchEvent( new Event( 'lazyload' ) ); | |
} | |
} ); | |
} ); | |
} | |
observer.observe( element ); | |
element.addEventListener( 'lazyload', callback, { once: true } ); | |
} | |
LazyLoad( document.getElementById( 'something' ), function() | |
{ | |
// `this` is the element | |
console.log( this ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment