Chapter 56: Resource Hints & Preloading

Dynamic & Predictive Preloading with JavaScript

**Part 12: Performance & Optimization** — Chapter 56: Resource Hints & Preloading

LEARNING OBJECTIVES
  • Dynamically inject <link rel="prefetch"> and <link rel="preload"> tags using JavaScript.
  • Implement hover and viewport intersection link prefetching (Quicklink / Instant.page pattern).
  • Respect user Data-Saver modes (navigator.connection.saveData) and battery state before prefetching.
  • Measure navigation speedups from predictive route prefetching.
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

💻 Interactive Code Playground


class PredictivePrefetcher {
  constructor() {
    this.prefetched = new Set();
    this.init();
  }

  init() {
    // Respect user's 2G connection or Save-Data preference
    if (navigator.connection && (navigator.connection.saveData || /2g/.test(navigator.connection.effectiveType))) {
      console.log('Prefetching disabled due to slow connection or data-saver mode.');
      return;
    }

    // Prefetch links on mouse hover or touchstart
    document.addEventListener('mouseover', (e) => this.handleEvent(e));
    document.addEventListener('touchstart', (e) => this.handleEvent(e), { passive: true });
  }

  handleEvent(e) {
    const link = e.target.closest('a');
    if (!link || !link.href) return;

    const url = new URL(link.href, window.location.href);
    if (url.origin !== window.location.origin || this.prefetched.has(url.pathname)) return;

    this.prefetch(url.href);
    this.prefetched.add(url.pathname);
  }

  prefetch(href) {
    const link = document.createElement('link');
    link.rel = 'prefetch';
    link.href = href;
    document.head.appendChild(link);
  }
}

new PredictivePrefetcher();

📌 Key Takeaways

  • Predictive prefetching on link hover provides a 200–300ms head-start before the user finishes clicking.
  • Always check navigator.connection.saveData to avoid wasting cellular data on metered connections.
  • --

❓ Knowledge Check

1. Which of the following is correct?

2. Which of the following is correct?