Skip to content

Instantly share code, notes, and snippets.

@walfie
Last active April 10, 2024 12:52
Show Gist options
  • Save walfie/a80c4432bcff70fb826d5d28158e9cc4 to your computer and use it in GitHub Desktop.
Save walfie/a80c4432bcff70fb826d5d28158e9cc4 to your computer and use it in GitHub Desktop.
Run webworker from `file://`, with working `importScripts`
<script>
function createWebWorkerFromFunction(f) {
var blobContents = ['(', f.toString(), ')();'];
var blob = new Blob(blobContents, { type: 'application/javascript'});
var blobUrl = URL.createObjectURL(blob);
var worker = new Worker(blobUrl);
URL.revokeObjectURL(blobUrl);
return worker;
}
var worker = createWebWorkerFromFunction(function() {
self.onmessage = function(e) {
importScripts(e.data.scriptUrl);
}
});
var workerUrl = (function() {
var parts = document.location.href.split('/');
parts[parts.length - 1] = 'worker.js';
return parts.join('/');
}());
worker.onmessage = function(e) {
console.log('main received message: ' + e.data);
}
// Send the worker the path to load the script from
worker.postMessage({ scriptUrl: workerUrl });
// Assuming worker.js has loaded the script and overwrote its `self.onmessage`
worker.postMessage('ping');
worker.postMessage('hello');
</script>
onmessage = function(e) {
console.log('worker received message: ' + e.data)
if (e.data == 'ping') {
postMessage('pong');
} else {
postMessage('unknown message');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment