UNPKG

mytril

Version:

Mytril Svelte library component for rapidly building modern websites based on Svelte and Sveltekit

29 lines (28 loc) 956 B
export const useLazyImg = (node, { root = null, rootMargin = '0px 0px 0px 0px', threshold = 0.0 } = {}) => { if (typeof window !== 'undefined' && 'IntersectionObserver' in window) { const observer = new IntersectionObserver((entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { const image = entry.target; if (image.dataset.src) { image.src = image.dataset.src; } if (image.dataset.srcset) { image.srcset = image.dataset.srcset; } observer.unobserve(image); } }); }, { root, rootMargin, threshold }); observer.observe(node); return { destroy() { observer.unobserve(node); } }; } };