问题
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?
回答1:
The spec at http://www.w3.org/TR/2015/WD-workers-20150924/#communicating-with-a-dedicated-worker says
The implicit MessagePort used by dedicated workers has its port message queue implicitly enabled when it is created
Also
https://developer.mozilla.org/en/docs/Web/API/Worker/postMessage doesn't mention having to wait for the worker to load before sending messages
Testing posting messages immediately after creating a worker that can't be in the cache http://plnkr.co/edit/jM1qy9lDEFKYhR0TDsKa?p=preview
var worker = new Worker('worker.js?' + (new Date()).getTime()); worker.postMessage(''); worker.postMessage('');
with the worker just outputting to the console
self.onmessage = function() { console.log('received'); }
has always shown 2 console messages for me when testing. This isn't a guarantee that it will always work this way though, but given that I'm trying to make it lose messages and failing, it is reasonable evidence.
回答2:
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.
来源:https://stackoverflow.com/questions/34409254/are-messages-sent-via-worker-postmessage-queued