class Media {
|
constructor() {
|
this.currentWidth = window.innerWidth;
|
this.images = document.querySelectorAll('.wp-site-blocks img[data-small]');
|
|
if (this.images.length === 0) return;
|
|
// Immediately load visible images
|
this.loadVisibleImages();
|
|
this.initListeners();
|
}
|
|
loadVisibleImages() {
|
// Load first image immediately, plus any in viewport
|
this.images.forEach((img, index) => {
|
const rect = img.getBoundingClientRect();
|
const isVisible = rect.top < window.innerHeight && rect.bottom > 0;
|
|
// Always load first image, or if currently visible
|
if (index === 0 || isVisible) {
|
this.loadAppropriateImage(img);
|
img.dataset.loaded = 'true'; // Mark so we don't observe it
|
}
|
});
|
}
|
|
initListeners() {
|
this.resizeHandler = this.handleResize.bind(this);
|
window.addEventListener('resize', this.resizeHandler);
|
|
// Only observe images that weren't immediately loaded
|
this.observer = new IntersectionObserver((entries) => {
|
entries.forEach(entry => {
|
if (entry.isIntersecting) {
|
this.loadAppropriateImage(entry.target);
|
this.observer.unobserve(entry.target);
|
}
|
});
|
}, {
|
rootMargin: '50px',
|
threshold: 0.1
|
});
|
|
this.images.forEach(img => {
|
if (!img.dataset.loaded) {
|
this.observer.observe(img);
|
}
|
});
|
}
|
|
handleResize() {
|
window.debouncer.schedule('image-resize', () => {
|
const newWidth = window.innerWidth;
|
if (Math.abs(newWidth - this.currentWidth) > 100) {
|
this.currentWidth = newWidth;
|
this.updateVisibleImages();
|
}
|
}, 150);
|
}
|
|
updateVisibleImages() {
|
this.images.forEach(img => {
|
const rect = img.getBoundingClientRect();
|
if (rect.top < window.innerHeight && rect.bottom > 0) {
|
this.loadAppropriateImage(img, true);
|
}
|
});
|
}
|
|
loadAppropriateImage(img, forceUpdate = false) {
|
const targetSize = this.getTargetSize();
|
const newSrc = img.dataset[targetSize];
|
|
if (newSrc && (forceUpdate || newSrc !== img.currentSrc)) {
|
img.src = newSrc;
|
}
|
}
|
|
getTargetSize() {
|
if (this.currentWidth < 768) return 'small';
|
if (this.currentWidth < 1200) return 'medium';
|
return 'full';
|
}
|
|
cleanup() {
|
this.observer?.disconnect();
|
window.removeEventListener('resize', this.resizeHandler);
|
}
|
}
|
|
window.isLoaded = false;
|
document.addEventListener('readystatechange', () => {
|
if (!window.isLoaded && document.querySelector('.wp-site-blocks img')) {
|
window.jvbMedia = new Media();
|
window.isLoaded = true;
|
}
|
});
|