Lazy Loading Images and Iframes

Implements native lazy loading for images and iframes using the loading attribute, with Intersection Observer fallback for older browsers.

HtmlFile Upload

Code

snippet
<!-- Native lazy loading -->
<img src="hero.jpg" alt="Hero" loading="eager" width="1200" height="600">
<img src="image1.jpg" alt="Image 1" loading="lazy" width="400" height="300">
<img src="image2.jpg" alt="Image 2" loading="lazy" width="400" height="300">
<img src="image3.jpg" alt="Image 3" loading="lazy" width="400" height="300">

<iframe src="video-player.html" loading="lazy"
        width="560" height="315"
        title="Video player"></iframe>

<!-- With fade-in effect -->
<img class="lazy-img"
     src="placeholder.svg"
     data-src="actual-image.jpg"
     alt="Description"
     width="400" height="300">

<style>
  .lazy-img {
    opacity: 0;
    transition: opacity 0.3s;
  }
  .lazy-img.loaded {
    opacity: 1;
  }
</style>

<script>
  if ('IntersectionObserver' in window) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target;
          img.src = img.dataset.src;
          img.classList.add('loaded');
          observer.unobserve(img);
        }
      });
    }, {
      rootMargin: '50px 0px',
      threshold: 0.01
    });

    document.querySelectorAll('img[data-src]').forEach(img => {
      observer.observe(img);
    });
  } else {
    document.querySelectorAll('img[data-src]').forEach(img => {
      img.src = img.dataset.src;
    });
  }
</script>