37 lines
1017 B
TypeScript
37 lines
1017 B
TypeScript
/**
|
||
* Автоматическая ленивая подгрузка фоновых изображений с 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 {};
|