We use cookies to enhance your experience on the site
CodeWorlds

Performance and Event Optimization

How to ensure high performance with intensive event usage.

Performance Optimizations

1// Passive event listeners for better scroll performance
2window.addEventListener('scroll', handleScroll, { passive: true });
3window.addEventListener('touchstart', handleTouch, { passive: true });
4
5// Event listener only once
6button.addEventListener('click', handleClick, { once: true });
7
8// Capture phase
9button.addEventListener('click', handleClick, { capture: true });
10
11// Combination of options
12element.addEventListener('scroll', handleScroll, {
13  passive: true,
14  capture: false,
15  once: false
16});
17
18// Intersection Observer instead of scroll events
19const observer = new IntersectionObserver((entries) => {
20  entries.forEach(entry => {
21    if (entry.isIntersecting) {
22      // Element entered the viewport
23      loadLazyContent(entry.target);
24    }
25  });
26}, {
27  rootMargin: '100px' // Trigger 100px before entering the viewport
28});
29
30// Observe elements
31document.querySelectorAll('.lazy-load').forEach(el => {
32  observer.observe(el);
33});
34
35// ResizeObserver instead of resize events
36const resizeObserver = new ResizeObserver(entries => {
37  entries.forEach(entry => {
38    const { width, height } = entry.contentRect;
39    updateElementLayout(entry.target, width, height);
40  });
41});
42
43resizeObserver.observe(document.getElementById('responsive-element'));
Go to CodeWorlds