Chapter 55: Screen Orientation & Device APIs

The Network Information API

Inspect live network bandwidth, latency, cellular connection types, and `saveData` modes using `navigator.connection` for dynamic adaptive asset loading.

LEARNING OBJECTIVES
  • Access connection telemetry via navigator.connection (NetworkInformation interface).
  • Evaluate effectiveType (4g, 3g, 2g, slow-2g) to measure real-world network quality over raw radio specs.
  • Read estimated throughput with downlink (Mbps) and round-trip latency with rtt (ms).
  • Honor the user's explicit bandwidth preferences by checking the saveData boolean flag.
  • Implement an adaptive media pipeline that loads low-res thumbnails on 2G/Save-Data and HD assets on high-speed 4G/Wi-Fi.
🎬 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.

📖 The Mental Model & Story (Intuitive Foundation)

Imagine watching a video on Netflix while traveling on a commuter train. As the train enters a deep mountain tunnel, your cellular signal drops from high-speed 5G down to a patchy 3G connection. If the video player kept trying to download a 4K 60fps stream, playback would freeze with an endless buffering spinner. Instead, the video engine seamlessly drops the video bitrate to 720p or 480p, keeping playback smooth without interruption.

                  [ PHYSICAL NETWORK MODEM (Wi-Fi / 5G / LTE) ]
                                         │
                                         ▼
                     +───────────────────────────────────────+
                     │          navigator.connection         │
                     │    (NetworkInformation Interface)     │
                     +───────────────────────────────────────+
                                         │
         ┌───────────────────────────────┼───────────────────────────────┐
         ▼                               ▼                               ▼
 [ EFFECTIVE QUALITY ]           [ LATENCY & SPEED ]             [ USER PREFERENCE ]
 - effectiveType: '4g'|'3g'      - downlink: 10.5 Mbps           - saveData: true|false
 - type: 'wifi'|'cellular'       - rtt: 50 ms
         │                               │                               │
         └───────────────────────────────┼───────────────────────────────┘
                                         │
                                         ▼
                     +───────────────────────────────────────+
                     │       ADAPTIVE ASSET PIPELINE         │
                     │ • High Speed ('4g' & !saveData):      │
                     │   - Load 4K AVIF hero images          │
                     │   - Pre-fetch next 3 routes in SPA    │
                     │ • Degraded ('3g'|'2g' | saveData):    │
                     │   - Load lightweight WebP / JPEG      │
                     │   - Disable auto-playing video        │
                     │   - Defer non-critical analytics      │
                     +───────────────────────────────────────+

The W3C Network Information API brings this exact adaptive intelligence to client-side web development through navigator.connection.


Technical Deep Dive & Specifications

The NetworkInformation Interface

interface NavigatorNetworkInformation {
  readonly attribute NetworkInformation connection;
}

interface NetworkInformation extends EventTarget {
  readonly attribute ConnectionType? type;             // 'wifi', 'cellular', 'ethernet', etc.
  readonly attribute EffectiveConnectionType effectiveType; // 'slow-2g', '2g', '3g', '4g'
  readonly attribute Megabits downlink;               // Bandwidth in Mbps (rounded)
  readonly attribute Milliseconds rtt;                // Latency in ms (nearest 25ms)
  readonly attribute boolean saveData;                // True if user enabled Data-Saver
  
  attribute EventHandler onchange;
}

type EffectiveConnectionType = 'slow-2g' | '2g' | '3g' | '4g';
type ConnectionType = 'bluetooth' | 'cellular' | 'ethernet' | 'mixed' | 'none' | 'other' | 'unknown' | 'wifi' | 'wimax';

Effective Connection Type (ECT) vs Physical Type

Why does the W3C specify effectiveType instead of just physical type? A smartphone might be connected to a physical 5G or Wi-Fi radio, but if it is connected to an overloaded hotel router or poor cell tower, real-world data speeds might crawl at 200 Kbps.

effectiveType classifies connection quality based on measured Round Trip Time (RTT) and Downlink Bandwidth:

Effective Type (effectiveType) Minimum Downlink (Mbps) Maximum RTT (ms) Target Experience
slow-2g $< 0.05\text{ Mbps}$ ($\le 50\text{ Kbps}$) $\ge 2000\text{ ms}$ Extremely degraded. Serve minimal text only. Disable all background scripts.
2g $0.05 \text{ to } 0.25\text{ Mbps}$ $1400 \text{ to } 2000\text{ ms}$ Serve low-res compressed images. No video autoplay.
3g $0.25 \text{ to } 0.70\text{ Mbps}$ $270 \text{ to } 1400\text{ ms}$ Standard web experience. Compressed WebP/JPEG.
4g $\ge 0.70\text{ Mbps}$ $< 270\text{ ms}$ High-performance experience. Uncompressed media, pre-fetching, 1080p/4K video.

The saveData Attribute

When a user enables "Data Saver" mode in their mobile OS or browser (e.g. Chrome Lite Mode / Android Data Saver), navigator.connection.saveData evaluates to true.

                    User enables Data-Saver in OS/Browser
                                     │
                                     ▼
                ┌────────────────────────────────────────┐
                │ HTTP Header:    Save-Data: on          │
                │ JavaScript:     navigator.connection   │
                │                 .saveData === true     │
                └────────────────────────────────────────┘

[!IMPORTANT] When saveData === true, professional frontend architectures must respect the user's financial data cap regardless of whether they currently sit on high-speed 4G or Wi-Fi.


💻 Interactive Code Playground

Starter Code

Line-by-Line Code Breakdown

  • Lines 131–142: Implements vendor-prefixed cross-browser feature detection (navigator.connection || navigator.mozConnection || navigator.webkitConnection).
  • Lines 144–147: Reads key attributes: effectiveType, downlink (Mbps), rtt (ms), and the user's saveData boolean flag.
  • Lines 150–154: Populates the live UI metric fields.
  • Lines 167–178: Implements the Adaptive Asset Loading Decision Engine:
    • If saveData === true or on 2g/slow-2g: Automatically selects a 28 KB WebP thumbnail.
    • If on 3g: Selects a 320 KB standard image.
    • If on 4g: Delivers the 3.4 MB full Ultra-HD AVIF experience.
  • Lines 181–184: Subscribes to the change event on navigator.connection to react dynamically if network conditions change mid-session.

Expected Browser Render Output


SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...
📡 Network Telemetry & Adaptive Loader
Inspects real-time bandwidth metrics and throttles asset payloads dynamically.

[ ● Connection: 4G ]

EFFECTIVE TYPE (ECT)             ESTIMATED DOWNLINK
4g                               10.0 Mbps

ROUND TRIP TIME (RTT)            SAVE-DATA MODE
50 ms                            Disabled (OFF)

+-------------------------------------------------------------+
|               🎬 Ultra-HD Hero (4K AVIF)                    |
|               Target payload: 3.4 MB                        |
+-------------------------------------------------------------+

🏋️ Hands-On Exercise

🎯 The Challenge: Build a Smart Adaptive Video Autoplay Manager

Instructions:

  1. Create an HTML5 <video> tag with muted and playsinline attributes.
  2. Build an asset manager function loadAdaptiveVideo(videoElement) that:
    • Checks navigator.connection.
    • If on 4g and saveData === false, sets video.src = 'high-res-1080p.mp4', enables autoplay, and starts playback.
    • If on 3g, sets video.src = 'medium-res-720p.mp4' with autoplay.
    • If on 2g or saveData === true, aborts video download entirely, sets poster = 'fallback-poster.jpg', and renders a button: "Tap to play video (Conserves Data)".

🏁 Starter Code Sandbox

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
STARTER CODE SANDBOX exercise.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

⚠️ Common Pitfalls

  1. Equating Wi-Fi with High Speed: Just because conn.type === 'wifi' does not mean the user has fast internet. A congested public airport Wi-Fi may report effectiveType === 'slow-2g'. Always base decisions on effectiveType, downlink, and rtt.
  2. Over-Quantized Metrics: To prevent fingerprinting, browsers intentionally quantize rtt to the nearest 25ms and clamp maximum downlink (e.g. capped at 10 Mbps on Chrome). Do not expect microsecond precision.
  3. Ignoring Safari Incompatibility: Apple Safari does not support navigator.connection. Always provide a fallback default (e.g. conn?.effectiveType || '4g') so code does not throw errors.

💡 Pro Tips

  1. Client-Hints Server Integration: Modern browsers send HTTP request headers like Save-Data: on, Downlink: 10, ECT: 4g, and RTT: 50 directly to your web server (via Accept-CH: ECT, Downlink, RTT, Save-Data), enabling the CDN to resize images before they are sent to HTML.
  2. Combine with Service Worker Caching: On 2g or saveData, serve strictly from Service Worker Cache without querying network fallback.

📌 Key Takeaways

  • navigator.connection exposes the NetworkInformation interface.
  • effectiveType categorizes connection quality into 'slow-2g', '2g', '3g', or '4g' based on real RTT and throughput.
  • saveData indicates explicit user intent to conserve cellular megabytes.
  • downlink estimates bandwidth in Megabits per second (Mbps); rtt estimates round-trip latency in milliseconds.
  • The change event listener allows web apps to dynamically adjust video bitrates and image quality on the fly.
  • --
⭐ LEARN: HTML 🌟 ⚔️ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

Why is effectiveType generally more useful for adaptive asset loading than physical type (e.g. 'wifi')?

Question 1 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 2 / 3

What action should your web application take when navigator.connection.saveData === true?

Question 2 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 3 / 3

Which event should you listen to on navigator.connection to react when a user moves between 4G and 3G coverage?

Question 3 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP