After creating a worker, I can send messages to it via postMessage
. For example:
var worker = new Worker('helper.js');
worker.postMessage({...});
Inside helper.js, the worker needs to add a listener using onmessage = function (event) { ... };
My question is, if one or more messages are sent to the worker while the worker script is still loading, is it guaranteed that the messages get queued and delivered eventually, or is it possible that they may get lost?
Simply add a custom toString-method on the object. When trying to send an object with postMessage in IE8 and IE9 they will be converted to a string with the toString-method on the object. Since browsers that support sending objects doesn't call toString we can use this to our advantage.
You need to use the postMessage() method in the onmessage event handler in worker. js : // src/worker. js onmessage = e => { const message = e.
Messages will be queued while the worker script is being downloaded and parsed by the browser, but onmessage
must be defined synchronously in the worker (at least in Chrome v56).
The following will not fully work:
worker.js:
setTimeout(function() {
onmessage = function() {
console.log('received message');
}
}, 0);
main-script.js:
var worker = new Worker('worker.js');
worker.postMessage('first message'); // this won't go through
setTimeout(function() {
worker.postMessage('second message'); // this will
}, 1000);
The worker's onmessage
function will only fire for the second message.
I've demonstrated this issue in this plunkr: http://embed.plnkr.co/G54gk9Cz6XhZ3E6ZB3Nf/
importScripts
does stop execution in the worker until the scripts are downloaded, so waiting until after that to define onmessage
should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With