Web Foundations

HTML Performance

Resource hints, lazy loading, async/defer scripts, and optimization.

Advertisement

HTML Performance

Resource hints, lazy loading, async/defer scripts, and optimization.

Overview

Performance optimization improves loading speed and user experience.

Key Concepts

  • Resource Hints — Preload, prefetch, preconnect
  • Lazy Loading — Load on demand
  • Async/Defer — Script loading strategies
  • Critical CSS — Inline above-fold styles
  • Compression — Gzip/Brotli encoding

Code Examples

<head>
  <!-- Preconnect to third-party origins -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  
  <!-- Preload critical resources -->
  <link rel="preload" href="/fonts/main.woff2" as="font" type="font/woff2" crossorigin>
  <link rel="preload" href="/css/critical.css" as="style">
  <link rel="preload" href="/js/app.js" as="script">
  
  <!-- Prefetch for next navigation -->
  <link rel="prefetch" href="/about.js">
  <link rel="prefetch" href="/contact.js">
  
  <!-- DNS prefetch -->
  <link rel="dns-prefetch" href="https://api.example.com">
  
  <!-- Critical CSS inline -->
  <style>
    /* Above-fold styles only */
    body { margin: 0; font-family: sans-serif; }
    .hero { padding: 2rem; background: #f5f5f5; }
  </style>
  
  <!-- Async script (no dependencies) -->
  <script src="/js/analytics.js" async></script>
  
  <!-- Defer script (preserves order) -->
  <script src="/js/app.js" defer></script>
  
  <!-- Module scripts are deferred by default -->
  <script type="module" src="/js/module.js"></script>
</head>

<body>
  <!-- Lazy load images -->
  <img src="image.jpg" alt="Eagerly loaded" width="800" height="600">
  <img src="image2.jpg" alt="Lazy loaded" loading="lazy" width="800" height="600">
  
  <!-- Lazy load iframes -->
  <iframe src="https://www.youtube.com/embed/..." loading="lazy" width="560" height="315"></iframe>
  
  <!-- Intersection Observer for lazy loading -->
  <div data-src="content.html" class="lazy-load">Loading...</div>
  
  <script>
  // Lazy load with Intersection Observer
  const lazyElements = document.querySelectorAll('[data-src]');
  
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const element = entry.target;
        element.src = element.dataset.src;
        element.classList.add('loaded');
        observer.unobserve(element);
      }
    });
  });
  
  lazyElements.forEach(el => observer.observe(el));
  
  // Resource timing API
  window.addEventListener('load', () => {
    const resources = performance.getEntriesByType('resource');
    resources.forEach(resource => {
      console.log(`${resource.name}: ${resource.duration}ms`);
    });
  });
  </script>
</body>

Practice

Optimize a webpage's loading performance using resource hints and lazy loading.

Advertisement