Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Web Workers Patterns Guide

Web Workers Patterns Guide

Offload heavy computations to Web Workers for responsive Google Antigravity applications.

web-workersperformanceconcurrencytypescript
by antigravity-team
⭐0Stars
.antigravity
# Web Workers Patterns for Google Antigravity

Web Workers enable running JavaScript in background threads, keeping your UI responsive during heavy computations. This guide covers effective patterns for Web Workers in Google Antigravity projects.

## Basic Worker Setup

```typescript
// workers/computation.worker.ts
self.onmessage = async (event: MessageEvent) => {
    const { type, payload } = event.data;
    
    switch (type) {
        case "PROCESS_DATA":
            const result = await processLargeDataset(payload);
            self.postMessage({ type: "RESULT", payload: result });
            break;
        case "CALCULATE":
            const calculation = performHeavyCalculation(payload);
            self.postMessage({ type: "CALCULATION_DONE", payload: calculation });
            break;
    }
};

function processLargeDataset(data: number[]): number[] {
    return data.map((item) => {
        let result = item;
        for (let i = 0; i < 1000; i++) {
            result = Math.sqrt(result * result + i);
        }
        return result;
    });
}

function performHeavyCalculation(params: { iterations: number; seed: number }): number {
    let value = params.seed;
    for (let i = 0; i < params.iterations; i++) {
        value = (value * 1103515245 + 12345) % 2147483648;
    }
    return value;
}

export {};
```

## Worker Manager Class

```typescript
// lib/worker-manager.ts
export class WorkerManager<TInput, TOutput> {
    private worker: Worker | null = null;
    private pending: Map<string, { resolve: (value: TOutput) => void; reject: (error: Error) => void }> = new Map();

    constructor(private workerPath: string) {}

    private getWorker(): Worker {
        if (!this.worker) {
            this.worker = new Worker(new URL(this.workerPath, import.meta.url));
            this.worker.onmessage = (event) => {
                const { id, result, error } = event.data;
                const pending = this.pending.get(id);
                if (pending) {
                    if (error) pending.reject(new Error(error));
                    else pending.resolve(result);
                    this.pending.delete(id);
                }
            };
            this.worker.onerror = (error) => console.error("Worker error:", error);
        }
        return this.worker;
    }

    execute(type: string, payload: TInput): Promise<TOutput> {
        return new Promise((resolve, reject) => {
            const id = crypto.randomUUID();
            this.pending.set(id, { resolve, reject });
            this.getWorker().postMessage({ id, type, payload });
        });
    }

    terminate(): void {
        this.worker?.terminate();
        this.worker = null;
        this.pending.clear();
    }
}
```

## React Hook for Workers

```typescript
// hooks/useWorker.ts
import { useRef, useCallback, useEffect, useState } from "react";

export function useWorker<TInput, TOutput>(workerPath: string) {
    const workerRef = useRef<Worker | null>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<Error | null>(null);
    const [result, setResult] = useState<TOutput | null>(null);

    useEffect(() => {
        workerRef.current = new Worker(new URL(workerPath, import.meta.url));
        workerRef.current.onmessage = (event) => { setResult(event.data.payload); setLoading(false); };
        workerRef.current.onerror = (e) => { setError(new Error(e.message)); setLoading(false); };
        return () => { workerRef.current?.terminate(); };
    }, [workerPath]);

    const execute = useCallback((type: string, payload: TInput) => {
        setLoading(true);
        setError(null);
        workerRef.current?.postMessage({ type, payload });
    }, []);

    return { execute, result, loading, error };
}
```

## Worker Pool for Parallel Processing

```typescript
// lib/worker-pool.ts
export class WorkerPool<T> {
    private workers: Worker[] = [];
    private queue: Array<{ task: T; resolve: (result: unknown) => void }> = [];
    private activeWorkers = 0;

    constructor(private workerPath: string, private poolSize: number = navigator.hardwareConcurrency || 4) {
        for (let i = 0; i < this.poolSize; i++) {
            this.workers.push(new Worker(new URL(workerPath, import.meta.url)));
        }
    }

    async executeAll(tasks: T[]): Promise<unknown[]> {
        return Promise.all(tasks.map((task) => this.execute(task)));
    }

    private execute(task: T): Promise<unknown> {
        return new Promise((resolve) => {
            this.queue.push({ task, resolve });
            this.processQueue();
        });
    }

    private processQueue(): void {
        if (this.queue.length === 0 || this.activeWorkers >= this.poolSize) return;
        const { task, resolve } = this.queue.shift()!;
        const worker = this.workers[this.activeWorkers];
        this.activeWorkers++;
        worker.onmessage = (event) => { this.activeWorkers--; resolve(event.data); this.processQueue(); };
        worker.postMessage(task);
    }

    terminate(): void {
        this.workers.forEach((w) => w.terminate());
        this.workers = [];
        this.queue = [];
    }
}
```

## Best Practices

1. **Structured Cloning**: Be aware of data transfer costs; use Transferable objects for large buffers
2. **Error Handling**: Always handle worker errors to prevent silent failures
3. **Pool Management**: Use worker pools for parallel processing of multiple tasks
4. **Cleanup**: Terminate workers when components unmount to prevent memory leaks
5. **Fallbacks**: Provide main-thread fallbacks for environments without Worker support

When to Use This Prompt

This web-workers prompt is ideal for developers working on:

  • web-workers applications requiring modern best practices and optimal performance
  • Projects that need production-ready web-workers code with proper error handling
  • Teams looking to standardize their web-workers development workflow
  • Developers wanting to learn industry-standard web-workers patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their web-workers implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the web-workers code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this web-workers prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For web-workers projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...