mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
hanzoskills.com/llms.txt now opens with the install line, the API reference index and the company index, so an agent that lands on any one of the three can find the rest. robots.txt claimed 537 documents while llms.txt counts 920. The number is gone from robots.txt; llms.txt derives it. public/ is regenerated from scripts/site.py, which it had fallen behind: the copy-prompt menu and agent bar were in the generator and not in the committed pages. tests/site.mjs passes against the result. Co-authored-by: Hanzo Dev <[email protected]>
831 lines
34 KiB
HTML
831 lines
34 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>frontend-browser-concurrency</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/frontend-browser-concurrency.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/frontend-browser-concurrency">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/frontend-browser-concurrency.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>frontend-browser-concurrency</h1><p class="lede">Service Workers, SharedWorkers, Worklets, and multi-threading patterns for advanced browser concurrency</p><h1>Browser Concurrency</h1>
|
|
<p><strong>Scope</strong>: Service Workers, SharedWorkers, Worklets, OffscreenCanvas, multi-threading patterns, concurrent JavaScript <strong>Lines</strong>: ~400 <strong>Last Updated</strong>: 2025-10-27</p>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Implementing offline functionality and PWAs</li><li>Building shared worker pools across tabs</li><li>Creating audio/animation worklets</li><li>Managing background sync and push notifications</li><li>Implementing advanced caching strategies</li><li>Building real-time collaborative applications</li><li>Need coordination between multiple browser contexts</li></ul>
|
|
<hr>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Browser Concurrency Model</h3>
|
|
<p><strong>Thread Types</strong>:</p>
|
|
<ol><li><strong>Main Thread</strong> - UI rendering, DOM manipulation</li><li><strong>Web Workers</strong> - Dedicated background threads (see <code>web-workers.md</code>)</li><li><strong>Service Workers</strong> - Network proxy, offline support, background sync</li><li><strong>SharedWorkers</strong> - Shared thread across multiple tabs/windows</li><li><strong>Worklets</strong> - Lightweight workers for rendering pipeline (Audio, Paint, Animation)</li></ol>
|
|
<p><strong>Context Types</strong>:</p>
|
|
<ul><li><strong>Window</strong> - Main browser tab context</li><li><strong>Worker</strong> - Dedicated worker global scope</li><li><strong>ServiceWorkerGlobalScope</strong> - Service worker context</li><li><strong>SharedWorkerGlobalScope</strong> - Shared worker context</li><li><strong>WorkletGlobalScope</strong> - Worklet context</li></ul>
|
|
<hr>
|
|
<h2>Service Workers</h2>
|
|
<h3>PWA and Offline Support</h3>
|
|
<p><strong>Lifecycle</strong>: Install → Activate → Fetch</p>
|
|
<p><strong>service-worker.ts</strong>:</p>
|
|
<pre><code class="lang-typescript">/// <reference lib="webworker" />
|
|
|
|
declare const self: ServiceWorkerGlobalScope;
|
|
|
|
const CACHE_NAME = 'app-cache-v1';
|
|
const ASSETS = [
|
|
'/',
|
|
'/index.html',
|
|
'/styles.css',
|
|
'/app.js',
|
|
'/manifest.json'
|
|
];
|
|
|
|
// Install: Cache assets
|
|
self.addEventListener('install', (event: ExtendableEvent) => {
|
|
console.log('[SW] Installing...');
|
|
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
console.log('[SW] Caching assets');
|
|
return cache.addAll(ASSETS);
|
|
})
|
|
);
|
|
|
|
// Take control immediately
|
|
self.skipWaiting();
|
|
});
|
|
|
|
// Activate: Clean old caches
|
|
self.addEventListener('activate', (event: ExtendableEvent) => {
|
|
console.log('[SW] Activating...');
|
|
|
|
event.waitUntil(
|
|
caches.keys().then((cacheNames) => {
|
|
return Promise.all(
|
|
cacheNames
|
|
.filter((name) => name !== CACHE_NAME)
|
|
.map((name) => caches.delete(name))
|
|
);
|
|
})
|
|
);
|
|
|
|
// Take control of all clients
|
|
self.clients.claim();
|
|
});
|
|
|
|
// Fetch: Cache-first strategy
|
|
self.addEventListener('fetch', (event: FetchEvent) => {
|
|
const { request } = event;
|
|
|
|
event.respondWith(
|
|
caches.match(request).then((cached) => {
|
|
if (cached) {
|
|
console.log('[SW] Cache hit:', request.url);
|
|
return cached;
|
|
}
|
|
|
|
console.log('[SW] Fetching:', request.url);
|
|
return fetch(request).then((response) => {
|
|
// Cache successful responses
|
|
if (response.ok) {
|
|
const clone = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
cache.put(request, clone);
|
|
});
|
|
}
|
|
|
|
return response;
|
|
});
|
|
})
|
|
);
|
|
});</code></pre>
|
|
<p><strong>Register service worker</strong>:</p>
|
|
<pre><code class="lang-typescript">// main.ts
|
|
async function registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {
|
|
if ('serviceWorker' in navigator) {
|
|
try {
|
|
const registration = await navigator.serviceWorker.register('/sw.js', {
|
|
scope: '/'
|
|
});
|
|
|
|
console.log('SW registered:', registration.scope);
|
|
|
|
// Listen for updates
|
|
registration.addEventListener('updatefound', () => {
|
|
const newWorker = registration.installing;
|
|
console.log('SW update found');
|
|
|
|
newWorker?.addEventListener('statechange', () => {
|
|
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
|
|
// New version available
|
|
console.log('New SW installed, please reload');
|
|
}
|
|
});
|
|
});
|
|
|
|
return registration;
|
|
} catch (error) {
|
|
console.error('SW registration failed:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
// Initialize
|
|
registerServiceWorker();</code></pre>
|
|
<hr>
|
|
<h2>Caching Strategies</h2>
|
|
<h3>1. Cache First (Offline-First)</h3>
|
|
<pre><code class="lang-typescript">self.addEventListener('fetch', (event: FetchEvent) => {
|
|
event.respondWith(
|
|
caches.match(event.request).then((cached) => {
|
|
return cached || fetch(event.request);
|
|
})
|
|
);
|
|
});</code></pre>
|
|
<h3>2. Network First (Fresh Content Priority)</h3>
|
|
<pre><code class="lang-typescript">self.addEventListener('fetch', (event: FetchEvent) => {
|
|
event.respondWith(
|
|
fetch(event.request)
|
|
.then((response) => {
|
|
// Cache successful response
|
|
const clone = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
cache.put(event.request, clone);
|
|
});
|
|
return response;
|
|
})
|
|
.catch(() => {
|
|
// Fallback to cache on network failure
|
|
return caches.match(event.request);
|
|
})
|
|
);
|
|
});</code></pre>
|
|
<h3>3. Stale-While-Revalidate</h3>
|
|
<pre><code class="lang-typescript">self.addEventListener('fetch', (event: FetchEvent) => {
|
|
event.respondWith(
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
return cache.match(event.request).then((cached) => {
|
|
const fetchPromise = fetch(event.request).then((response) => {
|
|
cache.put(event.request, response.clone());
|
|
return response;
|
|
});
|
|
|
|
// Return cached immediately, update in background
|
|
return cached || fetchPromise;
|
|
});
|
|
})
|
|
);
|
|
});</code></pre>
|
|
<h3>4. Cache with Network Fallback and Timeout</h3>
|
|
<pre><code class="lang-typescript">async function fetchWithTimeout(
|
|
request: Request,
|
|
timeout: number = 3000
|
|
): Promise<Response> {
|
|
const controller = new AbortController();
|
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
|
|
try {
|
|
const response = await fetch(request, { signal: controller.signal });
|
|
clearTimeout(timeoutId);
|
|
return response;
|
|
} catch (error) {
|
|
clearTimeout(timeoutId);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
self.addEventListener('fetch', (event: FetchEvent) => {
|
|
event.respondWith(
|
|
caches.match(event.request).then((cached) => {
|
|
if (cached) return cached;
|
|
|
|
return fetchWithTimeout(event.request, 3000).catch(() => {
|
|
return new Response('Offline', { status: 503 });
|
|
});
|
|
})
|
|
);
|
|
});</code></pre>
|
|
<hr>
|
|
<h2>Background Sync</h2>
|
|
<h3>Reliable Network Requests</h3>
|
|
<p><strong>service-worker.ts</strong>:</p>
|
|
<pre><code class="lang-typescript">// Register sync event
|
|
self.addEventListener('sync', (event: SyncEvent) => {
|
|
if (event.tag === 'sync-messages') {
|
|
event.waitUntil(syncMessages());
|
|
}
|
|
});
|
|
|
|
async function syncMessages(): Promise<void> {
|
|
const cache = await caches.open('pending-requests');
|
|
const requests = await cache.keys();
|
|
|
|
for (const request of requests) {
|
|
try {
|
|
const response = await fetch(request);
|
|
if (response.ok) {
|
|
await cache.delete(request);
|
|
console.log('Synced:', request.url);
|
|
}
|
|
} catch (error) {
|
|
console.error('Sync failed:', error);
|
|
}
|
|
}
|
|
}</code></pre>
|
|
<p><strong>Client-side request</strong>:</p>
|
|
<pre><code class="lang-typescript">async function sendMessage(message: string): Promise<void> {
|
|
try {
|
|
const response = await fetch('/api/messages', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ message })
|
|
});
|
|
|
|
if (!response.ok) throw new Error('Network error');
|
|
} catch (error) {
|
|
// Save for background sync
|
|
const cache = await caches.open('pending-requests');
|
|
await cache.put(
|
|
new Request('/api/messages', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ message })
|
|
}),
|
|
new Response()
|
|
);
|
|
|
|
// Register sync
|
|
const registration = await navigator.serviceWorker.ready;
|
|
await registration.sync.register('sync-messages');
|
|
}
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Push Notifications</h2>
|
|
<h3>Real-Time Updates</h3>
|
|
<p><strong>service-worker.ts</strong>:</p>
|
|
<pre><code class="lang-typescript">// Listen for push events
|
|
self.addEventListener('push', (event: PushEvent) => {
|
|
const data = event.data?.json() ?? { title: 'Notification', body: 'New message' };
|
|
|
|
event.waitUntil(
|
|
self.registration.showNotification(data.title, {
|
|
body: data.body,
|
|
icon: '/icon.png',
|
|
badge: '/badge.png',
|
|
tag: 'notification-1',
|
|
requireInteraction: false,
|
|
actions: [
|
|
{ action: 'open', title: 'Open' },
|
|
{ action: 'close', title: 'Close' }
|
|
]
|
|
})
|
|
);
|
|
});
|
|
|
|
// Handle notification clicks
|
|
self.addEventListener('notificationclick', (event: NotificationEvent) => {
|
|
event.notification.close();
|
|
|
|
if (event.action === 'open') {
|
|
event.waitUntil(
|
|
self.clients.openWindow('/')
|
|
);
|
|
}
|
|
});</code></pre>
|
|
<p><strong>Subscribe to push</strong>:</p>
|
|
<pre><code class="lang-typescript">async function subscribeToPush(): Promise<PushSubscription | null> {
|
|
const registration = await navigator.serviceWorker.ready;
|
|
|
|
try {
|
|
const subscription = await registration.pushManager.subscribe({
|
|
userVisibleOnly: true,
|
|
applicationServerKey: urlBase64ToUint8Array(PUBLIC_VAPID_KEY)
|
|
});
|
|
|
|
// Send subscription to server
|
|
await fetch('/api/push/subscribe', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(subscription)
|
|
});
|
|
|
|
return subscription;
|
|
} catch (error) {
|
|
console.error('Push subscription failed:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function urlBase64ToUint8Array(base64String: string): Uint8Array {
|
|
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
|
|
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
|
|
const rawData = window.atob(base64);
|
|
return Uint8Array.from([...rawData].map((char) => char.charCodeAt(0)));
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>SharedWorkers</h2>
|
|
<h3>Cross-Tab Communication</h3>
|
|
<p><strong>shared-worker.ts</strong>:</p>
|
|
<pre><code class="lang-typescript">/// <reference lib="webworker" />
|
|
|
|
declare const self: SharedWorkerGlobalScope;
|
|
|
|
// Track all connected ports
|
|
const ports = new Set<MessagePort>();
|
|
let sharedState = { count: 0, users: [] as string[] };
|
|
|
|
self.addEventListener('connect', (event: MessageEvent) => {
|
|
const port = event.ports[0];
|
|
ports.add(port);
|
|
|
|
console.log('Client connected. Total:', ports.size);
|
|
|
|
// Send current state to new client
|
|
port.postMessage({
|
|
type: 'STATE',
|
|
payload: sharedState
|
|
});
|
|
|
|
port.addEventListener('message', (e: MessageEvent) => {
|
|
const { type, payload } = e.data;
|
|
|
|
switch (type) {
|
|
case 'INCREMENT':
|
|
sharedState.count++;
|
|
broadcast({ type: 'STATE', payload: sharedState });
|
|
break;
|
|
|
|
case 'ADD_USER':
|
|
sharedState.users.push(payload);
|
|
broadcast({ type: 'STATE', payload: sharedState });
|
|
break;
|
|
|
|
case 'RESET':
|
|
sharedState = { count: 0, users: [] };
|
|
broadcast({ type: 'STATE', payload: sharedState });
|
|
break;
|
|
}
|
|
});
|
|
|
|
port.start();
|
|
});
|
|
|
|
function broadcast(message: any): void {
|
|
ports.forEach((port) => {
|
|
port.postMessage(message);
|
|
});
|
|
}</code></pre>
|
|
<p><strong>Client usage</strong>:</p>
|
|
<pre><code class="lang-typescript">const sharedWorker = new SharedWorker(
|
|
new URL('./shared-worker.ts', import.meta.url),
|
|
{ type: 'module' }
|
|
);
|
|
|
|
sharedWorker.port.addEventListener('message', (event: MessageEvent) => {
|
|
const { type, payload } = event.data;
|
|
|
|
if (type === 'STATE') {
|
|
console.log('Shared state:', payload);
|
|
updateUI(payload);
|
|
}
|
|
});
|
|
|
|
sharedWorker.port.start();
|
|
|
|
// Send messages
|
|
function increment(): void {
|
|
sharedWorker.port.postMessage({ type: 'INCREMENT' });
|
|
}
|
|
|
|
function addUser(name: string): void {
|
|
sharedWorker.port.postMessage({ type: 'ADD_USER', payload: name });
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>React Integration with SharedWorker</h2>
|
|
<p><strong>useSharedWorker.ts</strong>:</p>
|
|
<pre><code class="lang-typescript">import { useEffect, useState, useRef } from 'react';
|
|
|
|
export function useSharedWorker<T>(workerUrl: string) {
|
|
const [state, setState] = useState<T | null>(null);
|
|
const workerRef = useRef<SharedWorker | null>(null);
|
|
|
|
useEffect(() => {
|
|
const worker = new SharedWorker(new URL(workerUrl, import.meta.url), {
|
|
type: 'module'
|
|
});
|
|
workerRef.current = worker;
|
|
|
|
worker.port.addEventListener('message', (event: MessageEvent) => {
|
|
const { type, payload } = event.data;
|
|
|
|
if (type === 'STATE') {
|
|
setState(payload);
|
|
}
|
|
});
|
|
|
|
worker.port.start();
|
|
|
|
return () => {
|
|
worker.port.close();
|
|
};
|
|
}, [workerUrl]);
|
|
|
|
const postMessage = (message: any) => {
|
|
if (workerRef.current) {
|
|
workerRef.current.port.postMessage(message);
|
|
}
|
|
};
|
|
|
|
return { state, postMessage };
|
|
}</code></pre>
|
|
<p><strong>Component</strong>:</p>
|
|
<pre><code class="lang-typescript">function SharedCounter() {
|
|
const { state, postMessage } = useSharedWorker<{ count: number }>('./shared-worker.ts');
|
|
|
|
return (
|
|
<div>
|
|
<p>Count (shared across tabs): {state?.count ?? 0}</p>
|
|
<button onClick={() => postMessage({ type: 'INCREMENT' })}>
|
|
Increment
|
|
</button>
|
|
</div>
|
|
);
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>Worklets</h2>
|
|
<h3>Audio Worklet (High-Performance Audio)</h3>
|
|
<p><strong>audio-processor.ts</strong>:</p>
|
|
<pre><code class="lang-typescript">/// <reference lib="webworker" />
|
|
|
|
class WhiteNoiseProcessor extends AudioWorkletProcessor {
|
|
process(
|
|
inputs: Float32Array[][],
|
|
outputs: Float32Array[][],
|
|
parameters: Record<string, Float32Array>
|
|
): boolean {
|
|
const output = outputs[0];
|
|
|
|
for (let channel = 0; channel < output.length; channel++) {
|
|
const outputChannel = output[channel];
|
|
|
|
for (let i = 0; i < outputChannel.length; i++) {
|
|
// Generate white noise
|
|
outputChannel[i] = Math.random() * 2 - 1;
|
|
}
|
|
}
|
|
|
|
// Return true to keep processor alive
|
|
return true;
|
|
}
|
|
}
|
|
|
|
registerProcessor('white-noise-processor', WhiteNoiseProcessor);</code></pre>
|
|
<p><strong>Using the worklet</strong>:</p>
|
|
<pre><code class="lang-typescript">async function playWhiteNoise(): Promise<void> {
|
|
const audioContext = new AudioContext();
|
|
|
|
// Load worklet module
|
|
await audioContext.audioWorklet.addModule('./audio-processor.ts');
|
|
|
|
// Create worklet node
|
|
const whiteNoiseNode = new AudioWorkletNode(audioContext, 'white-noise-processor');
|
|
|
|
// Connect to destination
|
|
whiteNoiseNode.connect(audioContext.destination);
|
|
|
|
// Start playback
|
|
await audioContext.resume();
|
|
}</code></pre>
|
|
<hr>
|
|
<h2>OffscreenCanvas</h2>
|
|
<h3>Rendering in Workers</h3>
|
|
<p><strong>canvas-worker.ts</strong>:</p>
|
|
<pre><code class="lang-typescript">self.addEventListener('message', (event: MessageEvent) => {
|
|
const { type, canvas } = event.data;
|
|
|
|
if (type === 'INIT' && canvas instanceof OffscreenCanvas) {
|
|
const ctx = canvas.getContext('2d')!;
|
|
let frame = 0;
|
|
|
|
function animate(): void {
|
|
// Clear canvas
|
|
ctx.fillStyle = 'black';
|
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
|
|
// Draw animation
|
|
ctx.fillStyle = 'white';
|
|
ctx.beginPath();
|
|
ctx.arc(
|
|
canvas.width / 2 + Math.cos(frame / 50) * 100,
|
|
canvas.height / 2 + Math.sin(frame / 50) * 100,
|
|
20,
|
|
0,
|
|
Math.PI * 2
|
|
);
|
|
ctx.fill();
|
|
|
|
frame++;
|
|
requestAnimationFrame(animate);
|
|
}
|
|
|
|
animate();
|
|
}
|
|
});</code></pre>
|
|
<p><strong>Main thread</strong>:</p>
|
|
<pre><code class="lang-typescript">const canvas = document.getElementById('canvas') as HTMLCanvasElement;
|
|
const offscreen = canvas.transferControlToOffscreen();
|
|
|
|
const worker = new Worker(new URL('./canvas-worker.ts', import.meta.url), {
|
|
type: 'module'
|
|
});
|
|
|
|
worker.postMessage({ type: 'INIT', canvas: offscreen }, [offscreen]);</code></pre>
|
|
<hr>
|
|
<h2>Communication Patterns</h2>
|
|
<h3>1. Broadcast Channel (Cross-Tab)</h3>
|
|
<pre><code class="lang-typescript">// Create channel
|
|
const channel = new BroadcastChannel('app-channel');
|
|
|
|
// Listen for messages
|
|
channel.addEventListener('message', (event: MessageEvent) => {
|
|
console.log('Received:', event.data);
|
|
updateUI(event.data);
|
|
});
|
|
|
|
// Send message to all tabs
|
|
channel.postMessage({ type: 'UPDATE', payload: { count: 42 } });
|
|
|
|
// Cleanup
|
|
channel.close();</code></pre>
|
|
<h3>2. MessageChannel (Point-to-Point)</h3>
|
|
<pre><code class="lang-typescript">// Create channel
|
|
const channel = new MessageChannel();
|
|
|
|
// Send port to worker
|
|
worker.postMessage({ port: channel.port2 }, [channel.port2]);
|
|
|
|
// Communicate through port
|
|
channel.port1.addEventListener('message', (event: MessageEvent) => {
|
|
console.log('Response:', event.data);
|
|
});
|
|
|
|
channel.port1.start();
|
|
channel.port1.postMessage({ type: 'REQUEST', payload: 'data' });</code></pre>
|
|
<hr>
|
|
<h2>Performance Considerations</h2>
|
|
<h3>Worker Overhead</h3>
|
|
<p><strong>Creation cost</strong>:</p>
|
|
<ul><li>Web Worker: ~5-10ms</li><li>Service Worker: ~10-20ms (first activation)</li><li>SharedWorker: ~10-15ms</li><li>Worklet: ~1-5ms</li></ul>
|
|
<p><strong>Message passing cost</strong>:</p>
|
|
<ul><li>Simple object: <1ms</li><li>Large object (1MB): 5-20ms</li><li>Transferable (1MB): <1ms</li></ul>
|
|
<p><strong>Best Practices</strong>:</p>
|
|
<ul><li>Reuse workers (don't create per-task)</li><li>Use transferable objects for large data</li><li>Batch messages when possible</li><li>Use SharedWorker for cross-tab state</li><li>Use Worklets for real-time audio/animation</li></ul>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<p><strong>Bad: Creating service worker per request</strong></p>
|
|
<pre><code class="lang-typescript">❌ async function fetchData() {
|
|
await navigator.serviceWorker.register('/sw.js');
|
|
return fetch('/api/data');
|
|
}</code></pre>
|
|
<p><strong>Good: Register once at app start</strong></p>
|
|
<pre><code class="lang-typescript">✅ // Register on app initialization
|
|
navigator.serviceWorker.register('/sw.js');
|
|
|
|
// Use normally
|
|
async function fetchData() {
|
|
return fetch('/api/data'); // Service worker intercepts
|
|
}</code></pre>
|
|
<p><strong>Bad: SharedWorker without cleanup</strong></p>
|
|
<pre><code class="lang-typescript">❌ const worker = new SharedWorker('./worker.js');
|
|
// Never closed, leaks resources</code></pre>
|
|
<p><strong>Good: Cleanup on unmount</strong></p>
|
|
<pre><code class="lang-typescript">✅ useEffect(() => {
|
|
const worker = new SharedWorker('./worker.js');
|
|
worker.port.start();
|
|
|
|
return () => {
|
|
worker.port.close(); // Cleanup
|
|
};
|
|
}, []);</code></pre>
|
|
<hr>
|
|
<h2>Browser Compatibility</h2>
|
|
<p>| Feature | Chrome | Firefox | Safari | Edge | |---------|--------|---------|--------|------| | Service Workers | 40+ | 44+ | 11.1+ | 17+ | | SharedWorkers | 4+ | 29+ | 16.4+ | 79+ | | BroadcastChannel | 54+ | 38+ | 15.4+ | 79+ | | Audio Worklet | 66+ | 76+ | 14.1+ | 79+ | | OffscreenCanvas | 69+ | 105+ | 16.4+ | 79+ | | Background Sync | 49+ | ❌ | ❌ | 79+ | | Push API | 50+ | 44+ | 16.4+ | 79+ |</p>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><strong>web-workers.md</strong> - Dedicated Web Workers fundamentals</li><li><strong>frontend-performance.md</strong> - Overall performance optimization</li><li><strong>react-state-management.md</strong> - State management patterns</li><li><strong>nextjs-app-router.md</strong> - Next.js PWA configuration</li></ul>
|
|
<hr>
|
|
<h2>Summary</h2>
|
|
<p>Browser concurrency enables powerful multi-threaded web applications:</p>
|
|
<p><strong>Key Takeaways</strong>:</p>
|
|
<ul><li>Service Workers for offline support and PWAs</li><li>SharedWorkers for cross-tab state sharing</li><li>Worklets for real-time audio/animation</li><li>BroadcastChannel for simple cross-tab messaging</li><li>Choose the right worker type for your use case</li><li>Handle lifecycle and cleanup properly</li><li>Test across browsers for compatibility</li></ul>
|
|
<p><strong>Decision Tree</strong>:</p>
|
|
<ul><li><strong>Offline/PWA</strong> → Service Worker</li><li><strong>Cross-tab state</strong> → SharedWorker or BroadcastChannel</li><li><strong>CPU-intensive</strong> → Web Worker (see web-workers.md)</li><li><strong>Audio processing</strong> → Audio Worklet</li><li><strong>Canvas in background</strong> → OffscreenCanvas + Web Worker</li><li><strong>Simple messaging</strong> → BroadcastChannel</li></ul>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/frontend-browser-concurrency.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |