dressed_for_succes_store/frontend/app/lazy-background.ts

37 lines
1017 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Автоматическая ленивая подгрузка фоновых изображений с data-bg
* Работает для элементов с классом .lazy-bg и атрибутом data-bg="url(...)"
*/
function lazyLoadBackgrounds() {
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const el = entry.target as HTMLElement;
const bg = el.dataset.bg;
if (bg) {
el.style.backgroundImage = bg;
el.removeAttribute('data-bg');
obs.unobserve(el);
}
}
});
}, {
rootMargin: '100px',
threshold: 0.01,
});
document.querySelectorAll<HTMLElement>('.lazy-bg[data-bg]').forEach(el => {
observer.observe(el);
});
}
if (typeof window !== 'undefined') {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', lazyLoadBackgrounds);
} else {
lazyLoadBackgrounds();
}
}
export {};