Last active
April 10, 2024 12:52
-
-
Save walfie/a80c4432bcff70fb826d5d28158e9cc4 to your computer and use it in GitHub Desktop.
Run webworker from `file://`, with working `importScripts`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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