Under normal circumstances, a Web Worker should be passed a URL of the script to execute.
However, a local function can also be used
This is done by converting a function to a string, converting that string to a Blob, and converting that Blob to an Object URL.
Code
The code to do this would look a bit like this:
/* Some code we want to use as Worker */
const workerCode = () => {
onmessage = event => {
postMessage('some message')
}
}
/* Create a Worker from the function */
const code = workerCode
.toString() // Convert the function to a string (Duh)
.slice(10,-3) // This removes the "() => {" and closing "\n}\n"
const blob = new Blob([code], {type: 'application/javascript'})
const worker = new Worker(URL.createObjectURL(blob))
/* Send a message to the Worker code */
worker.postMessage('Hello Worker!')
/* Receive a message from the Worker code */
worker.onmessage = function(event) {
event.data // The message received from the worker
}
Be aware that the workerCode
does not share the scope with its parent!
As it is a separate script, it also has no window
, document
, etc.