JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
PrevNext
performance
junior
loading

What is lazy loading and how do you implement it?

lazy-loading
code-splitting
react-lazy
intersection-observer
Quick Answer

Lazy loading defers loading non-critical resources until they're needed. For images, use loading="lazy" attribute. For JavaScript, use dynamic import() or React.lazy(). This reduces initial page load time and saves bandwidth.

Detailed Explanation

What Can Be Lazy Loaded:

  • Images below the fold
  • Videos and iframes
  • JavaScript modules
  • React components
  • Data/API calls

Native Browser Support:

  • loading="lazy" for images
  • loading="lazy" for iframes
  • Intersection Observer for custom

JavaScript Lazy Loading:

  • import() for modules
  • React.lazy() for components
  • Route-based code splitting

When to Lazy Load:

  • Content below the fold
  • Modals and dialogs
  • Route components
  • Heavy features

Code Examples

Native lazy loading
<!-- Lazy load images -->
<img src="below-fold.jpg" loading="lazy" alt="Description" />

<!-- Eager load above-the-fold images -->
<img src="hero.jpg" loading="eager" alt="Hero" />

<!-- Lazy load iframes -->
<iframe 
  src="https://youtube.com/embed/video" 
  loading="lazy"
  title="Video"
></iframe>

<!-- Lazy load with intersection observer fallback -->
<img 
  class="lazy"
  src="placeholder.jpg" 
  data-src="actual-image.jpg"
  alt="Description"
/>

<script>
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      img.classList.remove('lazy');
      observer.unobserve(img);
    }
  });
});

document.querySelectorAll('.lazy').forEach(img => observer.observe(img));
</script>

Resources

Web.dev - Lazy loading

article

React - Code Splitting

docs

Related Questions

How does code splitting work and when should you use it?

mid
bundling

How do you optimize images for web performance?

junior
images
Previous
How do you optimize images for web performance?
Next
What are the different types of caching for web applications?