131 commands · 8 cheat sheets · HTML
Networking and Offline master quick reference
Browse 131 commands from 8 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.
Networking and Offline · 16 commands
Fetch API and Streaming Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Fetch JSON | const response = await fetch('/api/items', { headers: { Accept: 'application/json' } }) | View examples |
| Reject an HTTP error | if (!response.ok) throw new Error(`HTTP ${response.status}`) | View examples |
| Consume JSON once | const data = await response.json() | View examples |
| Construct a Request | const request = new Request('/api/items', { method: 'GET', cache: 'no-cache' }) | View examples |
| Require a CORS response | await fetch('https://api.example/data', { mode: 'cors' }) | View examples |
| Include cross-origin credentials | await fetch(url, { mode: 'cors', credentials: 'include' }) | View examples |
| Enforce same-origin access | await fetch(url, { mode: 'same-origin' }) | View examples |
| Cancel with a controller | const controller = new AbortController(); fetch(url, { signal: controller.signal }) | View examples |
| Apply a deadline | await fetch(url, { signal: AbortSignal.timeout(5000) }) | View examples |
| Combine cancellation sources | const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]) | View examples |
| Acquire a byte reader | const reader = response.body.getReader() | View examples |
| Decode streamed text | const textStream = response.body.pipeThrough(new TextDecoderStream()) | View examples |
| Pipe with cancellation | await response.body.pipeTo(destination, { signal }) | View examples |
| Check body disturbance | if (response.bodyUsed) throw new Error('Body already consumed') | View examples |
| Clone before reading | const auditCopy = response.clone() | View examples |
| Upload a stream | await fetch('/upload', { method: 'POST', body: stream, duplex: 'half' }) | View examples |
Networking and Offline · 23 commands
HTML Script, Stylesheet, and Resource Loading Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Run a parser-blocking script | <script src="/js/config.js"></script> | View examples |
| Defer a classic script | <script src="/js/app.js" defer></script> | View examples |
| Load an independent script | <script src="/js/analytics.js" async></script> | View examples |
| Load a JavaScript module | <script type="module" src="/js/app.js"></script> | View examples |
| Embed an inline module | <script type="module">
import { start } from "/js/app.js"; start();
</script> | View examples |
| Import code on demand | const { openHelp } = await import("/js/help.js"); | View examples |
| Map a bare module name | <script type="importmap">
{"imports":{"app":"/js/app.js"}}
</script> | View examples |
| Prepare a module early | <link rel="modulepreload" href="/js/app.js"> | View examples |
| Provide a legacy fallback | <script nomodule src="/js/legacy.js"></script> | View examples |
| Load an external stylesheet | <link rel="stylesheet" href="/css/site.css"> | View examples |
| Apply styles to matching media | <link
rel="stylesheet"
href="/css/print.css"
media="print"> | View examples |
| Embed document styles | <style>.notice { color: #9a3412; }</style> | View examples |
| Import CSS from CSS | @import url("/css/theme.css"); | View examples |
| Preload a stylesheet | <link rel="preload" href="/css/critical.css" as="style"> | View examples |
| Preload a web font | <link
rel="preload"
href="/fonts/inter.woff2"
as="font"
type="font/woff2"
crossorigin> | View examples |
| Open a connection early | <link
rel="preconnect"
href="https://cdn.example.com"
crossorigin> | View examples |
| Resolve an origin early | <link
rel="dns-prefetch"
href="https://analytics.example.com"> | View examples |
| Fetch a likely future resource | <link rel="prefetch" href="/next-page.html"> | View examples |
| Prioritize an important image | <img
src="/images/hero.webp"
alt="Product dashboard overview"
width="1200"
height="630"
fetchpriority="high"> | View examples |
| Defer an off-screen embed | <iframe
src="/embed/report"
title="Quarterly report preview"
width="800"
height="450"
loading="lazy">
</iframe> | View examples |
| Verify a cross-origin script | <script
src="https://example.com/example-framework.js"
integrity="sha384-Li9vy3DqF8tnTXuiaAJuML3ky+er10rcgNR/VqsVpcw+ThHmYcwiB1pbOxEbzJr7"
crossorigin="anonymous">
</script> | View examples |
| Limit a resource referrer | <script
src="https://cdn.example.com/widget.js"
referrerpolicy="no-referrer">
</script> | View examples |
| Provide a no-script fallback | <noscript>
<p>
JavaScript is required to open the interactive chart.
</p>
</noscript> | View examples |
Networking and Offline · 14 commands
Push Notifications and App Badging Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Register a service worker | const registration = await navigator.serviceWorker.register('/sw.js', { scope: '/' }) | View examples |
| Wait for an active worker | const registration = await navigator.serviceWorker.ready | View examples |
| Request notification permission | const permission = await Notification.requestPermission() | View examples |
| Read current permission | if (Notification.permission === 'granted') enablePush() | View examples |
| Create a push subscription | await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }) | View examples |
| Reuse a subscription | const subscription = await registration.pushManager.getSubscription() | View examples |
| Unsubscribe locally | await subscription.unsubscribe() | View examples |
| Extend a push event | event.waitUntil(handlePush(event)) | View examples |
| Show a notification | await self.registration.showNotification(title, options) | View examples |
| Replace related notifications | { tag: 'inbox', renotify: false } | View examples |
| Handle a notification click | self.addEventListener('notificationclick', event => event.waitUntil(openApp(event))) | View examples |
| Find application windows | const windows = await clients.matchAll({ type: 'window', includeUncontrolled: true }) | View examples |
| Set an application badge | await navigator.setAppBadge(unreadCount) | View examples |
| Clear the application badge | await navigator.clearAppBadge() | View examples |
Networking and Offline · 14 commands
Service Workers and Offline Caching Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Register within a scope | navigator.serviceWorker.register('/app/sw.js', { scope: '/app/' }) | View examples |
| Wait for an active worker | const registration = await navigator.serviceWorker.ready | View examples |
| Check current control | const controlled = navigator.serviceWorker.controller !== null | View examples |
| Extend installation | event.waitUntil(precachePromise) | View examples |
| Open a named cache | const cache = await caches.open('app-shell-v4') | View examples |
| Precache required URLs | await cache.addAll(['/app/', '/app/offline.html']) | View examples |
| Extend activation | event.waitUntil(deleteOldCaches()) | View examples |
| Claim matching clients | await self.clients.claim() | View examples |
| Activate a waiting update | registration.waiting.postMessage({ type: 'ACTIVATE_UPDATE' }) | View examples |
| Provide a fetch response | event.respondWith(responsePromise) | View examples |
| Find a cached response | const cached = await caches.match(event.request) | View examples |
| Store a response clone | await cache.put(request, response.clone()) | View examples |
| Check for an update | await registration.update() | View examples |
| Observe new control | navigator.serviceWorker.addEventListener('controllerchange', reloadOnce) | View examples |
Networking and Offline · 14 commands
Web Locks and Cross-Tab Coordination Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Request an exclusive lock | await navigator.locks.request('sync', async lock => runSync()) | View examples |
| Detect Web Locks | if (!navigator.locks) useFallback() | View examples |
| Return a callback value | const result = await navigator.locks.request('cache', () => rebuildCache()) | View examples |
| Request a shared lock | await navigator.locks.request('catalog', { mode: 'shared' }, readCatalog) | View examples |
| Try without waiting | await navigator.locks.request('leader', { ifAvailable: true }, lock => lock && lead()) | View examples |
| Bound lock waiting | await navigator.locks.request('sync', { signal: AbortSignal.timeout(5000) }, synchronize) | View examples |
| Cancel a pending request | controller.abort(new DOMException('Navigation', 'AbortError')) | View examples |
| Hold leadership | await navigator.locks.request('primary', () => leadershipLifetime) | View examples |
| Broadcast state | const channel = new BroadcastChannel('app-coordination') | View examples |
| Close messaging | channel.close() | View examples |
| Order nested locks | for (const name of [...names].sort()) await acquire(name) | View examples |
| Snapshot lock state | const { held, pending } = await navigator.locks.query() | View examples |
| Use a storage transaction | const transaction = database.transaction(['queue'], 'readwrite') | View examples |
| Avoid reserved names | const lockName = `document:${documentId}` | View examples |
Networking and Offline · 14 commands
Web Workers and Messaging Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a dedicated worker | const worker = new Worker('/workers/tasks.js') | View examples |
| Create a module worker | new Worker('/workers/tasks.js', { type: 'module', name: 'tasks' }) | View examples |
| Send a typed message | worker.postMessage({ type: 'sum', id, values }) | View examples |
| Receive worker output | worker.addEventListener('message', event => use(event.data)) | View examples |
| Connect to a shared worker | const shared = new SharedWorker('/workers/shared.js', { name: 'counter' }) | View examples |
| Start a message port | shared.port.addEventListener('message', handler); shared.port.start() | View examples |
| Clone structured data | const copy = structuredClone({ map: new Map([['x', 1]]) }) | View examples |
| Transfer an ArrayBuffer | worker.postMessage({ buffer }, [buffer]) | View examples |
| Create a private channel | const { port1, port2 } = new MessageChannel() | View examples |
| Transfer a message port | worker.postMessage({ type: 'attach', port: port2 }, [port2]) | View examples |
| Close a port | port1.close() | View examples |
| Observe worker errors | worker.addEventListener('error', reportWorkerError) | View examples |
| Observe decode failures | worker.addEventListener('messageerror', reportBadMessage) | View examples |
| Terminate immediately | worker.terminate() | View examples |
Networking and Offline · 14 commands
WebRTC Peer Connections Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a peer connection | const pc = new RTCPeerConnection({ iceServers }) | View examples |
| Use expiring TURN credentials | iceServers: [{ urls: 'turn:turn.example.com:3478', username, credential }] | View examples |
| Add a local track | pc.addTrack(track, localStream) | View examples |
| Create a transceiver | pc.addTransceiver('video', { direction: 'recvonly' }) | View examples |
| Render remote media | pc.ontrack = event => { remoteVideo.srcObject = event.streams[0] ?? new MediaStream([event.track]) } | View examples |
| Create and signal an offer | await pc.setLocalDescription(); signal({ description: pc.localDescription }) | View examples |
| Apply a remote description | await pc.setRemoteDescription(description) | View examples |
| Signal ICE candidates | pc.onicecandidate = ({ candidate }) => candidate && signal({ candidate }) | View examples |
| Apply a remote candidate | await pc.addIceCandidate(candidate) | View examples |
| Restart failed ICE | pc.restartIce() | View examples |
| Create a data channel | const channel = pc.createDataChannel('chat', { ordered: true }) | View examples |
| Bound buffered data | channel.bufferedAmountLowThreshold = 65536 | View examples |
| Read connection statistics | const report = await pc.getStats() | View examples |
| Close the session | pc.getSenders().forEach(({ track }) => track?.stop()); pc.close() | View examples |
Networking and Offline · 22 commands
WebSockets and Server-Sent Events Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Open a WebSocket | const socket = new WebSocket('wss://realtime.example.com/v1') | View examples |
| Open an event stream | const events = new EventSource('/api/events') | View examples |
| Include cross-origin credentials | const events = new EventSource('https://events.example/stream', { withCredentials: true }) | View examples |
| Offer subprotocols | const socket = new WebSocket(url, ['realtime.v2', 'realtime.v1']) | View examples |
| Wait for an open connection | socket.addEventListener('open', handleOpen, { once: true }) | View examples |
| Check the ready state | if (socket.readyState === WebSocket.OPEN) socket.send(payload) | View examples |
| Start a normal close | socket.close(1000, 'view unmounted') | View examples |
| Send a JSON message | socket.send(JSON.stringify({ type: 'subscribe', topic: 'orders' })) | View examples |
| Receive a WebSocket message | socket.addEventListener('message', event => routeMessage(event.data)) | View examples |
| Receive binary as ArrayBuffer | socket.binaryType = 'arraybuffer' | View examples |
| Send binary data | socket.send(new Uint8Array([1, 2, 3])) | View examples |
| Inspect queued outgoing bytes | const queuedBytes = socket.bufferedAmount | View examples |
| Apply an outgoing high-water mark | if (socket.bufferedAmount
< 262144) socket.send(nextMessage) | View examples |
| Handle default SSE messages | events.addEventListener('message', event => render(JSON.parse(event.data))) | View examples |
| Handle a named SSE event | events.addEventListener('order.updated', handleOrderUpdate) | View examples |
| Read the last event ID | const cursor = event.lastEventId | View examples |
| Resume from an SSE cursor | Last-Event-ID: 1042 | View examples |
| Set the SSE retry delay | retry: 5000 | View examples |
| Send an SSE comment heartbeat | : heartbeat | View examples |
| Inspect EventSource state | if (events.readyState === EventSource.CONNECTING) showReconnecting() | View examples |
| Stop EventSource reconnects | events.close() | View examples |
| Restrict realtime endpoints | Content-Security-Policy: connect-src 'self' wss://realtime.example.com https://events.example.com | View examples |



