Skip to content

Instantly share code, notes, and snippets.

@xPaw
Last active October 20, 2020 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xPaw/a6c933d942d6a782ce057128ab8360fe to your computer and use it in GitHub Desktop.
Save xPaw/a6c933d942d6a782ce057128ab8360fe to your computer and use it in GitHub Desktop.
Lazy load elements when they appear in view using IntersectionObserver
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