HTML and CSS Reference
In-Depth Information
This code creates a global variable named worker to hold the SharedWorker reference. The ready()
function wires the click event handler of the Start Work button. In the click event handler, an instance of
SharedWorker is created. A JavaScript file path that this shared web worker is supposed to run
( SharedProcessing.js ) is passed in the constructor.
In the case of the Worker object, the message event is raised on the object. In the case of SharedWorker ,
however, the message event is raised on the port object of the SharedWorker instance. That's why the
addEventListener() method is called on the port object. addEventListener() wires an event handler
function— ReceiveMessageFromWorker() —to the message event. Next, you need to call the port object's
start() method to start that port. Finally, postMessage() is called on the port object, and a string message
is sent to the shared worker thread. The ReceiveMessageFromWorker() function that acts as the message
event handler is as follows:
function ReceiveMessageFromWorker(evt) {
This function simply displays in an alert box the data sent back by the shared worker thread.
This completes the web form-level code. Now let's see what goes in the SharedProcessing.js ile
(Listing 10-6).
Listing 10-6. Code Running in a Shared Web Worker
var port;
addEventListener("connect", ReceiveMessageFromPage, false);
function ReceiveMessageFromPage(evt) {
port = evt.ports[0];
port.addEventListener("message", SendMessageToPage, false);
function SendMessageToPage(evt) {
var date = new Date();
var currentDate = null;
do {
currentDate = new Date();
while (currentDate - date < 10000);
port.postMessage("Page said : " + +
"\r\n Shared Worker Replied : Hello Page!");
This code begins by creating a global variable named port to hold a reference to a port object.
Whenever a new SharedWorker object obtains a reference to a shared worker thread, the connect event is
raised. To receive any messages from the web form in which the SharedWorker object exists, you need to
handle this event. The addEventListener() method attaches an event-handler function—
ReceiveMessageFromPage() —to the connect event.
The ReceiveMessageFromPage() event-handler function grabs the port object of the incoming
communication using evt.ports[0] . Although it appears that the ports array might have more than one
Search WWH ::

Custom Search