AyCode.Blazor/AyCode.Blazor.Components/wwwroot/js/mgLazyLoadContentObserver.js

65 lines
2.1 KiB
JavaScript

// Lazy content observer - renders content only when visible in viewport
window.lazyContentObserver = {
_observers: new Map(),
observe: function (element, dotNetRef, rootMargin, threshold) {
if (!element) {
console.error('[MgLazyLoadContent] Element not found');
return false;
}
// Clean up existing observer for this element
this.unobserve(element);
const options = {
root: null, // viewport
rootMargin: rootMargin || '50px',
threshold: threshold || 0.01
};
// Check immediate visibility before setting up observer
const rect = element.getBoundingClientRect();
const isCurrentlyVisible = (
rect.top < window.innerHeight &&
rect.bottom > 0 &&
rect.left < window.innerWidth &&
rect.right > 0
);
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
// Invoke .NET callback
dotNetRef.invokeMethodAsync('OnVisibilityChanged', entry.isIntersecting)
.catch(err => console.error('[MgLazyLoadContent] Callback error:', err));
});
}, options);
observer.observe(element);
this._observers.set(element, { observer, dotNetRef });
console.log('[MgLazyLoadContent] Observer initialized. Currently visible:', isCurrentlyVisible);
// Return immediate visibility status
return isCurrentlyVisible;
},
unobserve: function (element) {
if (!element) return;
const data = this._observers.get(element);
if (data) {
data.observer.disconnect();
this._observers.delete(element);
console.log('[MgLazyLoadContent] Observer removed');
}
},
dispose: function () {
this._observers.forEach((data, element) => {
data.observer.disconnect();
});
this._observers.clear();
console.log('[MgLazyLoadContent] All observers disposed');
}
};