window.onmessage = ...
window.postMessage('1', '*');
window.postMessage('2', '*');
Does postMessage
(http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.h开发者_StackOverflow中文版tml#queue-a-task) guarantee the order of events?
I don't know, although the wording of the spec seems to suggest it doesn't make such guarantees (which is surprising). It's clear that once the MessageEvent
is added to the task queue
on the receiving end, then it's order is maintained, although the MessageEvent
creation and dispatch are asynchronous to the original postMessage
call, so theoretically it appears that you could have the following situation:
main thread:
window.postMessage('1', '*'); --> thread spawned to create MessageEvent
window.postMessage('2', '*'); --> new thread spawned for another MessageEvent
If the thread management system allowed the second postMessage
to execute before the first thread managed to dispatch the MessageEvent
, and for whatever unlucky reason allowed that newer thread to execute (a diluted priority inversion), again before the first managed to dispatch, then you would indeed receive those messages in the reverse order.
Although there might be some other place in the spec that provides more context for these asynchronous executions and rules out this case - I couldn't find it.
window.postMessage()
only triggers a message event on being invoked, and as with classic event publish-subscribe mechanism, there is not real guarantee of the order in their order.
精彩评论