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

Open full cheat sheet
UseSyntaxExamples
Fetch JSONconst response = await fetch('/api/items', { headers: { Accept: 'application/json' } })View examples
Reject an HTTP errorif (!response.ok) throw new Error(`HTTP ${response.status}`)View examples
Consume JSON onceconst data = await response.json()View examples
Construct a Requestconst request = new Request('/api/items', { method: 'GET', cache: 'no-cache' })View examples
Require a CORS responseawait fetch('https://api.example/data', { mode: 'cors' })View examples
Include cross-origin credentialsawait fetch(url, { mode: 'cors', credentials: 'include' })View examples
Enforce same-origin accessawait fetch(url, { mode: 'same-origin' })View examples
Cancel with a controllerconst controller = new AbortController(); fetch(url, { signal: controller.signal })View examples
Apply a deadlineawait fetch(url, { signal: AbortSignal.timeout(5000) })View examples
Combine cancellation sourcesconst signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)])View examples
Acquire a byte readerconst reader = response.body.getReader()View examples
Decode streamed textconst textStream = response.body.pipeThrough(new TextDecoderStream())View examples
Pipe with cancellationawait response.body.pipeTo(destination, { signal })View examples
Check body disturbanceif (response.bodyUsed) throw new Error('Body already consumed')View examples
Clone before readingconst auditCopy = response.clone()View examples
Upload a streamawait fetch('/upload', { method: 'POST', body: stream, duplex: 'half' })View examples

Networking and Offline · 23 commands

HTML Script, Stylesheet, and Resource Loading Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
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 demandconst { 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

Open full cheat sheet
UseSyntaxExamples
Register a service workerconst registration = await navigator.serviceWorker.register('/sw.js', { scope: '/' })View examples
Wait for an active workerconst registration = await navigator.serviceWorker.readyView examples
Request notification permissionconst permission = await Notification.requestPermission()View examples
Read current permissionif (Notification.permission === 'granted') enablePush()View examples
Create a push subscriptionawait registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey })View examples
Reuse a subscriptionconst subscription = await registration.pushManager.getSubscription()View examples
Unsubscribe locallyawait subscription.unsubscribe()View examples
Extend a push eventevent.waitUntil(handlePush(event))View examples
Show a notificationawait self.registration.showNotification(title, options)View examples
Replace related notifications{ tag: 'inbox', renotify: false }View examples
Handle a notification clickself.addEventListener('notificationclick', event => event.waitUntil(openApp(event)))View examples
Find application windowsconst windows = await clients.matchAll({ type: 'window', includeUncontrolled: true })View examples
Set an application badgeawait navigator.setAppBadge(unreadCount)View examples
Clear the application badgeawait navigator.clearAppBadge()View examples

Networking and Offline · 14 commands

Service Workers and Offline Caching Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Register within a scopenavigator.serviceWorker.register('/app/sw.js', { scope: '/app/' })View examples
Wait for an active workerconst registration = await navigator.serviceWorker.readyView examples
Check current controlconst controlled = navigator.serviceWorker.controller !== nullView examples
Extend installationevent.waitUntil(precachePromise)View examples
Open a named cacheconst cache = await caches.open('app-shell-v4')View examples
Precache required URLsawait cache.addAll(['/app/', '/app/offline.html'])View examples
Extend activationevent.waitUntil(deleteOldCaches())View examples
Claim matching clientsawait self.clients.claim()View examples
Activate a waiting updateregistration.waiting.postMessage({ type: 'ACTIVATE_UPDATE' })View examples
Provide a fetch responseevent.respondWith(responsePromise)View examples
Find a cached responseconst cached = await caches.match(event.request)View examples
Store a response cloneawait cache.put(request, response.clone())View examples
Check for an updateawait registration.update()View examples
Observe new controlnavigator.serviceWorker.addEventListener('controllerchange', reloadOnce)View examples

Networking and Offline · 14 commands

Web Locks and Cross-Tab Coordination Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Request an exclusive lockawait navigator.locks.request('sync', async lock => runSync())View examples
Detect Web Locksif (!navigator.locks) useFallback()View examples
Return a callback valueconst result = await navigator.locks.request('cache', () => rebuildCache())View examples
Request a shared lockawait navigator.locks.request('catalog', { mode: 'shared' }, readCatalog)View examples
Try without waitingawait navigator.locks.request('leader', { ifAvailable: true }, lock => lock && lead())View examples
Bound lock waitingawait navigator.locks.request('sync', { signal: AbortSignal.timeout(5000) }, synchronize)View examples
Cancel a pending requestcontroller.abort(new DOMException('Navigation', 'AbortError'))View examples
Hold leadershipawait navigator.locks.request('primary', () => leadershipLifetime)View examples
Broadcast stateconst channel = new BroadcastChannel('app-coordination')View examples
Close messagingchannel.close()View examples
Order nested locksfor (const name of [...names].sort()) await acquire(name)View examples
Snapshot lock stateconst { held, pending } = await navigator.locks.query()View examples
Use a storage transactionconst transaction = database.transaction(['queue'], 'readwrite')View examples
Avoid reserved namesconst lockName = `document:${documentId}`View examples

Networking and Offline · 14 commands

Web Workers and Messaging Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a dedicated workerconst worker = new Worker('/workers/tasks.js')View examples
Create a module workernew Worker('/workers/tasks.js', { type: 'module', name: 'tasks' })View examples
Send a typed messageworker.postMessage({ type: 'sum', id, values })View examples
Receive worker outputworker.addEventListener('message', event => use(event.data))View examples
Connect to a shared workerconst shared = new SharedWorker('/workers/shared.js', { name: 'counter' })View examples
Start a message portshared.port.addEventListener('message', handler); shared.port.start()View examples
Clone structured dataconst copy = structuredClone({ map: new Map([['x', 1]]) })View examples
Transfer an ArrayBufferworker.postMessage({ buffer }, [buffer])View examples
Create a private channelconst { port1, port2 } = new MessageChannel()View examples
Transfer a message portworker.postMessage({ type: 'attach', port: port2 }, [port2])View examples
Close a portport1.close()View examples
Observe worker errorsworker.addEventListener('error', reportWorkerError)View examples
Observe decode failuresworker.addEventListener('messageerror', reportBadMessage)View examples
Terminate immediatelyworker.terminate()View examples

Networking and Offline · 14 commands

WebRTC Peer Connections Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a peer connectionconst pc = new RTCPeerConnection({ iceServers })View examples
Use expiring TURN credentialsiceServers: [{ urls: 'turn:turn.example.com:3478', username, credential }]View examples
Add a local trackpc.addTrack(track, localStream)View examples
Create a transceiverpc.addTransceiver('video', { direction: 'recvonly' })View examples
Render remote mediapc.ontrack = event => { remoteVideo.srcObject = event.streams[0] ?? new MediaStream([event.track]) }View examples
Create and signal an offerawait pc.setLocalDescription(); signal({ description: pc.localDescription })View examples
Apply a remote descriptionawait pc.setRemoteDescription(description)View examples
Signal ICE candidatespc.onicecandidate = ({ candidate }) => candidate && signal({ candidate })View examples
Apply a remote candidateawait pc.addIceCandidate(candidate)View examples
Restart failed ICEpc.restartIce()View examples
Create a data channelconst channel = pc.createDataChannel('chat', { ordered: true })View examples
Bound buffered datachannel.bufferedAmountLowThreshold = 65536View examples
Read connection statisticsconst report = await pc.getStats()View examples
Close the sessionpc.getSenders().forEach(({ track }) => track?.stop()); pc.close()View examples

Networking and Offline · 22 commands

WebSockets and Server-Sent Events Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Open a WebSocketconst socket = new WebSocket('wss://realtime.example.com/v1')View examples
Open an event streamconst events = new EventSource('/api/events')View examples
Include cross-origin credentialsconst events = new EventSource('https://events.example/stream', { withCredentials: true })View examples
Offer subprotocolsconst socket = new WebSocket(url, ['realtime.v2', 'realtime.v1'])View examples
Wait for an open connectionsocket.addEventListener('open', handleOpen, { once: true })View examples
Check the ready stateif (socket.readyState === WebSocket.OPEN) socket.send(payload)View examples
Start a normal closesocket.close(1000, 'view unmounted')View examples
Send a JSON messagesocket.send(JSON.stringify({ type: 'subscribe', topic: 'orders' }))View examples
Receive a WebSocket messagesocket.addEventListener('message', event => routeMessage(event.data))View examples
Receive binary as ArrayBuffersocket.binaryType = 'arraybuffer'View examples
Send binary datasocket.send(new Uint8Array([1, 2, 3]))View examples
Inspect queued outgoing bytesconst queuedBytes = socket.bufferedAmountView examples
Apply an outgoing high-water markif (socket.bufferedAmount < 262144) socket.send(nextMessage)View examples
Handle default SSE messagesevents.addEventListener('message', event => render(JSON.parse(event.data)))View examples
Handle a named SSE eventevents.addEventListener('order.updated', handleOrderUpdate)View examples
Read the last event IDconst cursor = event.lastEventIdView examples
Resume from an SSE cursorLast-Event-ID: 1042View examples
Set the SSE retry delayretry: 5000View examples
Send an SSE comment heartbeat: heartbeatView examples
Inspect EventSource stateif (events.readyState === EventSource.CONNECTING) showReconnecting()View examples
Stop EventSource reconnectsevents.close()View examples
Restrict realtime endpointsContent-Security-Policy: connect-src 'self' wss://realtime.example.com https://events.example.comView examples
CMDMEMO TERMINALREAD ONLY