Inline Workers with Blob URLs
What you'll learn: How to create web workers from inline JavaScript strings instead of separate files, simplifying your build process and deployment.
Why Inline Workers?
So far, you've created workers by pointing to external .js files. But what if you want to keep your worker code bundled with your main application? Writing worker code as a string and converting it to a worker on-the-fly makes bundling simpler and eliminates extra HTTP requests.
The Technique
You can create a worker from an inline string by:
- Writing your worker code as a string (or template literal)
- Creating a Blob from that string with MIME type
'text/javascript' - Generating a temporary URL using
URL.createObjectURL() - Passing that URL to the Worker constructor
Think of it like writing a recipe on a piece of paper (the Blob), then creating a temporary address (URL) where your kitchen assistant (the browser) can find and follow those instructions.
Code Example
// Worker code as a string
const workerCode = `
self.onmessage = function(e) {
const result = e.data * 2;
self.postMessage(result);
};
`;
// Create Blob and URL
const blob = new Blob([workerCode], { type: 'text/javascript' });
const workerUrl = URL.createObjectURL(blob);
// Create worker from the Blob URL
const worker = new Worker(workerUrl);
worker.onmessage = (e) => {
console.log('Result:', e.data);
};
worker.postMessage(5); // Logs: Result: 10
// Clean up when done
worker.terminate();
URL.revokeObjectURL(workerUrl);
Always remember to call URL.revokeObjectURL() when you're finished to free memory.
Key Takeaway: Inline workers using Blob URLs let you bundle worker logic directly in your main JavaScript, avoiding separate files while maintaining the performance benefits of off-main-thread execution.