Modern Web APIs

Modern browsers provide powerful APIs for building rich web applications. Understanding these APIs is essential for creating interactive and performant web experiences.

Intersection Observer

// Creating an intersection observer
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('visible');
    }
  });
}, {
  threshold: 0.5,
  rootMargin: '0px'
});

// Observing elements
document.querySelectorAll('.lazy-load')
  .forEach(el => observer.observe(el));

// Cleanup
observer.disconnect();

ResizeObserver

// Monitoring element size changes
const resizeObserver = new ResizeObserver(entries => {
  for (const entry of entries) {
    const { width, height } = entry.contentRect;
    console.log('Element size:', width, height);
  }
});

resizeObserver.observe(element);

Web Workers

// Main thread
const worker = new Worker('worker.js');

worker.postMessage({ data: complexData });

worker.onmessage = (event) => {
  console.log('Result:', event.data);
};

// worker.js
self.onmessage = (event) => {
  const result = heavyComputation(event.data);
  self.postMessage(result);
};

Service Workers

// Registering a service worker
navigator.serviceWorker.register('/sw.js')
  .then(registration => {
    console.log('SW registered');
  });

// sw.js
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll([
        '/',
        '/styles.css',
        '/app.js'
      ]);
    })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

Geolocation API

// Getting user location
navigator.geolocation.getCurrentPosition(
  position => {
    const { latitude, longitude } = position.coords;
    console.log(`Location: ${latitude}, ${longitude}`);
  },
  error => {
    console.error('Error:', error.message);
  },
  {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
  }
);

Web Share API

// Sharing content
async function shareContent() {
  try {
    await navigator.share({
      title: 'Check this out',
      text: 'Interesting article',
      url: window.location.href
    });
    console.log('Shared successfully');
  } catch (err) {
    console.error('Error sharing:', err);
  }
}

Common Interview Follow-up Questions

  1. How do you handle browser compatibility for modern APIs?
  2. What are the security considerations for Web Workers?
  3. How do Service Workers enable offline functionality?
  4. When would you use IntersectionObserver vs scroll events?

Best Practices

  • Always check for API support before using
  • Implement fallbacks for unsupported features
  • Consider performance implications
  • Handle errors and edge cases
  • Use feature detection instead of browser detection
  • Follow security best practices for workers