The Secret Life of JavaScript: The Observer
Source: Dev.to
Timothy leaned back in his chair, listening to the sudden, aggressive whir of his laptop fan. He had just finished implementing a lazy‑loading feature for a massive grid of user profile pictures.
“The scroll is perfectly smooth,” Timothy said, tapping his screen. “I used the
{ passive: true }flag we talked about yesterday. The Compositor Thread is completely unblocked. But my CPU usage just spiked to ninety percent, and my laptop sounds like it is preparing for takeoff.”
Margaret strolled over, coffee in hand, and peered at the performance monitor on his secondary display.
“You successfully unblocked the train,” Margaret said, nodding at the screen. “But you are torturing the dispatcher.”
The Problem with Scroll Polling
The code responsible for the lazy loading was tied directly to the scroll event:
const images = document.querySelectorAll('img[data-src]');
window.addEventListener('scroll', () => {
images.forEach(img => {
// Calculate exact geometry on every scroll tick
const rect = img.getBoundingClientRect();
// If the image enters the viewport, load it
if (rect.top {
entries.forEach(entry => {
// 2. Callback when the element intersects
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src; // Load the image
// 3. Stop observing once the image has loaded
observer.unobserve(img);
}
});
}, options);
// 4. Register all images with the observer
images.forEach(img => observer.observe(img));
The browser now performs all spatial calculations in its optimized C++ engine. JavaScript wakes up only when an image actually needs to be loaded, then immediately unobserves it to avoid repeated callbacks.
Benefits and Conclusion
- Reduced CPU usage – No continuous layout calculations on every scroll tick.
- Smoother scrolling – The Main Thread remains free for rendering and user interactions.
- Cleaner code – The observer pattern isolates the loading logic to a single, well‑scoped callback.
After switching to IntersectionObserver, Timothy refreshed the page and scrolled through the massive grid. The scrolling stayed buttery smooth, images appeared just before they entered view, and the laptop’s fan quieted down dramatically.