Skip to content
المشاريع

حول

An interactive platform demonstrating advanced Web Worker patterns and architectural strategies.

التعلّم والتعليم

كيف تُقاس هذه الأرقام

النمو المقاس للنجوم

خلال 24 ساعة
٠
خلال 7 أيام
٠
خلال 15 يومًا
٠
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

Mastering Web Workers

Field Value
Status Stable, with one caveat (see the note on example 12 below)
Last updated Tuesday, 29 September 2026

Note on example 12 (SharedArrayBuffer). It needs cross-origin isolation (COOP/COEP), and GitHub Pages can't send custom response headers. The app ships a service-worker shim (public/coi-serviceworker.js) that re-adds those headers client-side so crossOriginIsolated becomes true on the deployed demo. If isolation still isn't available, the example detects it at runtime and falls back to a clearly labelled simulated backend instead of failing silently. See example 12 for detail.

Angular TypeScript License

Interactive educational platform about Web Workers built with Angular 22. It ships 16 progressive examples with live demos and real thread visualization, told as a story in levels: main (the main thread, a living character) and the workers act each pattern out in an animated scene, and you clear a level by playing it. The UI is in Spanish, and the presentation is a swappable theme layer: today a single theme (default), with the engine kept generic so more themes (and languages) can be added without touching the domain.

▶ Live demo: damiansire.github.io/web-worker-patterns

Quick Start

On any system (Windows, macOS, Linux):

git clone https://github.com/damiansire/web-worker-patterns.git
cd web-worker-patterns
npm run dev

npm run dev checks Node.js (≥18) and npm (≥9), installs dependencies if needed, and starts the server at http://localhost:4200.

Alternatives:

  • Just start (if you already ran npm install): npm start
  • Windows: double-click scripts/start/start.bat, or in a terminal: npm run dev
  • macOS/Linux: in a terminal: ./scripts/start/start.sh or npm run dev

Open http://localhost:4200 in your browser.

Included Examples

The 16 examples are organized into 5 categories by concept. The grouping below mirrors src/app/core/domain/examples/examples.registry.ts, the single source of truth.

Understanding

# Example Description
01 Counter with setInterval How setInterval and the event loop work: the baseline to grasp before workers.
02 The main thread & event loop One thread runs JS, layout, paint and input; a 50 ms task freezes everything.
16 Compositor vs main The compositor thread keeps transform/opacity animations smooth even while the main thread is frozen.

Communication

# Example Description
03 Basic communication The "Hello World" of workers: postMessage in both directions.
08 SharedWorker One worker instance shared across tabs/panels, all seeing the same state.

Optimization

# Example Description
04 Offload heavy work Count primes on a worker so the UI stays responsive: feel the difference side by side.
07 Transferable objects Pass an ArrayBuffer zero-copy; the sender's buffer is left detached.
10 Worker pool A fixed pool of N workers drains a task queue (4 workers, 24 tasks).
14 OffscreenCanvas A worker owns the canvas and animates it: smooth even when the main thread blocks.
15 The cost of cloning Measure the real round-trip of structured clone as data size and complexity grow.

Management

# Example Description
05 Error handling A worker error doesn't crash the page; the main thread catches it.
06 Lifecycle & termination Create, run and terminate(): the in-flight step is lost and the worker can't be reused.
09 Limits of parallelism navigator.hardwareConcurrency caps real parallelism; beyond it, workers share cores.

Advanced

# Example Description
11 Backpressure Flow control with credits and acks so the worker's queue doesn't grow without bound.
12 SharedArrayBuffer Main and worker share the same memory; Atomics write/read with no postMessage. Needs cross-origin isolation (COOP/COEP). GitHub Pages can't send those headers, so the app registers a service-worker shim (coi-serviceworker.js) that adds them client-side and makes crossOriginIsolated === true on the deployed demo. If isolation is still unavailable, the demo detects it at runtime (crossOriginIsolated) and shows a labelled simulated backend instead of breaking.
13 Graceful degradation Detect typeof Worker and fall back to the main thread when it's missing.

The story in levels

The app reads like a course you play. A top bar and a level index on the side (chapters as folders, every level with its state and stars) frame each screen; the home page introduces the story with main alive on stage and a button to play the level that comes next. Each level is a lesson: on the left, the stage (an SVG + GSAP scene where main and the workers are characters) and the browser threads tape; on the right, the guide (the question, who is talking, what to do now, and the paths to choose), the code, which builds up step by step as things happen, and the level's stars as a checklist. The work is real (a loop that truly freezes the page, a real worker) and the scene shows the consequence: main freezes with everything it was juggling, the worker walks in and takes the job, clicks queue up while main is busy. Clearing a level means walking its pattern path; that unlocks the next one, and progress is saved locally. Every scripted level also gives up to three stars that make it worth replaying: clear it, see what happens on every path (the one that hurts included), and beat its challenge (for example, poking main while the worker computes, which proves with your own hands that main is still alive). The index shows the stars per level and the total, and has a "start over" button.

Chapter 1 (Understanding: 01, 02, 16) plus a prologue already have their scenes. The other levels are still under construction: they are always open from the index and play in their classic layout (demo, text and code) until their scene arrives. The level list and unlock rules live in story.levels.ts, the star rules in story.stars.ts and the save format in story.save.ts (all pure, unit-tested); what each level runs, in story.scripts.ts.

Visual Themes

The domain is skinned by a theme layer. Today there is one theme, default: "paper and ink" (cream paper, JetBrains Mono everywhere, hairline cards, ink-outlined pieces with a hard drop shadow, flat pastel fills), drawn from the semantic token contract plus its own --pp-* palette and a small kit of global pieces (pp-card, pp-btn, pp-tag...). The midnight (dark palette) and rpg (the journey as a game) themes were retired on 2026-11-08 to focus on a single experience; what the game proved (missions with a path that hurts, progress saved locally) lives on in the neutral core/domain/learning layer. The theming engine is still generic: a theme provides a shell, home, example layout, UI primitives and a thread visualizer, and is registered as a data-driven ThemePack. Adding a theme is adding entries to the registry, without the domain ever knowing a theme exists.

Project Architecture

The golden rule: the domain is written once; the presentation is a swappable theme layer. core/ is theme-neutral and never imports from themes/. The full rationale lives in ARQUITECTURA-multi-theme.md.

src/app/
├── core/                       # Neutral domain: knows nothing about themes
│   ├── domain/
│   │   ├── workers/            # Real Web Workers + pure *.logic.ts (unit-tested)
│   │   ├── examples/           # examples.registry.ts (source of truth) + code snippets
│   │   └── learning/           # The journey as a game: vocabulary, missions, progress (pure)
│   ├── services/               # Per-example demo services (signals-based)
│   ├── i18n/                   # Transloco loader
│   ├── styles/                 # Shared SCSS (_buttons, _containers, _example-layout)
│   └── utils/                  # Helpers (code-snippet.helper)
├── theming/                    # Theme registry, service, guard, token contract
├── ui-contracts/               # Interfaces every theme primitive must satisfy
├── ui-primitives/              # Theme-agnostic primitives (charts, language switcher)
├── themes/                     # Presentation: one folder per theme
│   └── default/                # The only theme (full token-driven presentation)
│       ├── shell/  story/  example-layout/  primitives/  styles/
├── app.routes.ts              # Routes generated from the examples registry
└── app.ts                     # Root component

public/i18n/                    # es.json (UI + per-example content)

Adding a New Example

A new example is one neutral domain definition rendered by the active theme. In short:

  1. Add the worker in core/domain/workers/ (+ a pure *.logic.ts with a unit test) and its snippets under core/domain/examples/snippets/.
  2. Register it in core/domain/examples/examples.registry.ts (id, order, category, demo, workerFactory).
  3. Add the educational content (title, summary, takeaways) to public/i18n/es.json.
  4. Wire the demo's visualization into the @case of the theme's example layout.

Routes, navigation and the home page update automatically from the registry.

Tech Stack

  • Angular 22: Standalone components, Signals, zoneless change detection (opt-in via provideZonelessChangeDetection()), esbuild-based build
  • TypeScript 6.0.3
  • SCSS: Semantic design tokens (--surface, --ink, --accent, --thread-*) per theme
  • @jsverse/transloco: Runtime i18n (ES; engine ready for more languages)
  • highlight.js: Syntax highlighting for code blocks
  • Vitest: Unit tests (297 tests across the pure domain logic, the services and the themes)
  • dependency-cruiser: Enforces the core/ ⇏ themes/ boundary
  • Web Workers API: Dedicated Workers, SharedWorker, Transferable Objects, SharedArrayBuffer + Atomics, OffscreenCanvas

This project uses Angular's built-in worker support (@angular/build / esbuild). Other setups use worker-plugin (webpack), rollup-plugin-off-main-thread, or Parcel's native worker support.

Performance benchmark

Clone cost is the thesis behind example 15: sending a payload across threads doesn't cost "crossing the thread" (that's sub-millisecond): it costs serializing and rebuilding the object graph, and that grows with size. Measure it yourself with the platform's own structuredClone (the same algorithm postMessage uses underneath):

npm run bench

Sample run (illustrative: numbers depend on your machine and Node version):

structured clone cost: median of 7 runs (Node v26.2.0)

  records |     JSON bytes |  clone ms
  --------+----------------+----------
     1000 |       38,666 B |     0.46
    10000 |      406,661 B |     4.51
    50000 |    2,122,226 B |    25.74
   200000 |    8,755,561 B |   171.98

The takeaway is the shape, not the exact numbers: clone cost scales with payload size. When it hurts, transfer (zero-copy, example 07) instead of cloning.

Angular Version

This project targets Angular 22 with @angular/build and a dedicated webWorkerTsConfig for worker bundles.

If you are upgrading from an older major version, use the Angular update tool and follow the official migration guidance:

ng update @angular/core @angular/cli

Then:

  • Zoneless (opt-in): Angular is not zoneless by default; this app enables it with provideZonelessChangeDetection() in app.config.ts (which is why it ships no zone.js in polyfills). It relies on Signals and computed() for change detection.
  • Tests: tsconfig.spec.json excludes **/*.worker.ts, so worker files are not compiled with the DOM Window type.
  • Build: @angular/build is the standard builder and bundles the app with esbuild.

Available Scripts

npm run dev            # Checks Node/npm, installs deps if needed and starts the server (all platforms)
npm start              # Dev server at localhost:4200 (requires a prior npm install)
npm run build          # Production build
npm test               # Gate: ESLint + ng build + unit tests (Vitest)
npm run test:e2e       # Real-browser gate: the production build served under a sub-path, as on Pages
npm run lint           # ESLint: no-console, mandatory OnPush, keyboard a11y
npm run format         # Format the code with Prettier
npm run format:check   # Check formatting without writing (CI gate)
npm run lint:boundaries# Enforce the golden rule (core/ ⇏ themes/)
npm run lint:style     # House style: no em dashes anywhere in the repo
npm run bench          # Reproducible structured-clone cost benchmark (example 15)

Quality gates (lint, build, format, tests, boundaries, house style and the real-browser e2e) run on every push/PR via CI and as a local git pre-commit hook, independent of your editor. ESLint enforces the invariants the repo preaches: no-console in the lib, ChangeDetectionStrategy.OnPush on every component (the app is zoneless), and keyboard a11y in templates. See AGENTS.md and docs/AI-PROCESS.md.

Language

The application UI is in Spanish, served via Transloco. Content lives in:

  • public/i18n/es.json: UI text and the educational content for every example

The i18n engine is kept generic: adding a language is adding its JSON in public/i18n/, its entry in LanguageService, and its code to availableLangs in app.config.ts. The neutral LanguageSwitcherComponent is ready to re-mount once there is more than one.

Privacy

The published demo sends one page view per screen to GoatCounter: the path, the page title, the referrer and the screen width. No cookies and no third-party script: it is a sendBeacon to the count endpoint, the only external host the CSP allows. It only runs on the GitHub Pages deploy; local, e2e and self-hosted builds send nothing. See page-view.logic.ts.

Documentation

Further reading

  • Use web workers to run JavaScript off the browser's main thread (web.dev): Why off-main-thread architecture helps Core Web Vitals (INP, LCP) and reduces main-thread contention.
  • Comlink: Use workers without writing postMessage by hand; expose an API that returns promises. This repo uses the native API to teach the fundamentals.
  • PROXX: Case study: Minesweeper clone with game logic in a worker and rendering on the main thread; see the web.dev article for the tradeoffs (reducing risk and improving UX rather than raw speed).

License

MIT

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…