Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active May 12, 2023 17:37
Show Gist options
  • Save crazy4groovy/c55a8ad5144219f6cd3854f2ee6f9648 to your computer and use it in GitHub Desktop.
Save crazy4groovy/c55a8ad5144219f6cd3854f2ee6f9648 to your computer and use it in GitHub Desktop.
Intersection Observer examples (JavaScript)
[...document.querySelectorAll('img[data-src]')].forEach((el, i) => {
const observer = new window.IntersectionObserver(function(entries, self) {
const {isIntersecting, target} = entries[0]
if (isIntersecting) {
const img = target
const src = img.getAttribute('data-src')
if (src) img.src = src
self.unobserve(img)
}
}, {})
observer.observe(el)
})
///////////// MORE EFFICIENT: A SINGLE OBSERVER! (with config) //////////////
function observeImages(
config = {
rootMargin: '0px 0px 50px 0px',
threshold: 0
},
attr = 'data-src'
) {
const observer = new IntersectionObserver((entries, self) => {
entries.forEach(({isIntersecting, target}) => {
if (isIntersecting) {
const img = target
const src = img.getAttribute(attr)
if (src) img.src = src
self.unobserve(img)
}
})
}, config)
[...document.querySelectorAll(`img[${attr}]`)].forEach(imgEl => observer.observe(imgEl))
return observer
}
// const imgObserver = observeImages()
export type Onload = (e: IntersectionObserverEntry) => void;
const isIntersectingLoadMap = new WeakMap<Element, Onload>();
const observer = new window.IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
entry.target.classList.toggle("__visible__", entry.isIntersecting);
if (!entry.isIntersecting) return;
const onload = isIntersectingLoadMap.get(entry.target);
if (onload) {
onload(entry);
observer.unobserve(entry.target);
}
});
},
{ threshold: 1, rootMargin: "10px" }
);
export default {
async observe(entry: Element, onload?: Onload) {
if (onload) isIntersectingLoadMap.set(entry, onload);
observer.observe(entry);
},
unobserve: observer.unobserve,
// disconnect: observer.disconnect,
};
function registerIntersectionObserver(el, cb, config = {}, parent = window) {
const observer = new parent.IntersectionObserver(function (entries, self) {
if (entries[0].isIntersecting) cb(self)
}, config)
observer.observe(el)
return observer
}
[...document.querySelectorAll('img')].forEach((imgEl, i) => {
const obs = registerIntersectionObserver(imgEl, (self) => {
console.log(i, imgEl.src)
obs.disconnect()
})
})
async function registerIntersectionObserver(el, config = {}, parent = window) {
return new Promise(res => {
const observer = new parent.IntersectionObserver(function (entries) {
if (entries[0].isIntersecting) res(observer)
}, config)
observer.observe(el)
})
}
[...document.querySelectorAll('img')].forEach(async (imgEl, i) => {
const observer = await registerIntersectionObserver(imgEl, {threshold: [0.1]})
observer.disconnect()
console.log(i, imgEl.src)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment