Skip to content

Instantly share code, notes, and snippets.

@andreasbotsikas
Created March 13, 2025 04:26
Show Gist options
  • Save andreasbotsikas/ff9a9dfdecc41ad6d6c39afa00615a2f to your computer and use it in GitHub Desktop.
Save andreasbotsikas/ff9a9dfdecc41ad6d6c39afa00615a2f to your computer and use it in GitHub Desktop.
Inline worker pattern
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Box and Worker Example</title>
</head>
<body>
<!-- Text input field -->
<form>
<input type="text" id="inputText" name="inputText">
</form>
<script>
// Get a reference to the text input element
var textBox = document.getElementById('inputText');
// Define the message handler for the main thread
function onmessage(e) {
// Update the text box with the message data from the worker
textBox.value = e.data;
}
// The inline worker is a workaround for environments like Cordova
// where workers loaded from the file:// protocol are restricted.
// It creates a worker from a Blob object which contains the worker's code as a string.
// This is inlined into the main script, so it doesn't need to be loaded from an external file.
// Credit goes to https://github.com/apache/cordova-android/issues/688
// Create a blob URL representing the worker script
const workerBlob = new Blob([
"(" + inlineWorker.toString() + ")()"
], { type: 'text/javascript' });
// Create the worker using the blob URL
const worker = new Worker(URL.createObjectURL(workerBlob));
// Set up the message event listener for the worker
worker.addEventListener('message', onmessage);
// Start the worker by posting a message to it
worker.postMessage(1337);
// Inline worker function that will run in the worker's context
function inlineWorker() {
// The self reference is used inside Web Workers to refer to the global context
self.addEventListener("message", startCounter);
function startCounter(event) {
let initial = event.data;
// Use self.postMessage to send messages from the worker to the main thread
setInterval(() => self.postMessage(initial++), 1000);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment