HTML and CSS Reference
In-Depth Information
This would be useful for applications, for example, like Gmail
or Facebook, where there may be some client-side data that
needs to be maintained, such as the messages for the user,
and you have several different windows open.
The worker can access and manage the website's client-side
Web SQL Databases (discussed in Chapter 6) and it can also
maintain the connection with the server, handling all the data
that's coming in and out or even via a Web Socket to the server
so that data is handled in real-time. The shared worker can then
maintain all of the changes to the client-side messages data-
base and then push all of those updates via postMessage to each
of the popups, iframes, and so on.
This means that there's no getting data out of sync or race condi-
tions if each of the popups, iframes, etc. was individually connect-
ing to the server and trying to each manage the client side, since
the shared worker is the single point of contact for all of that type
of work.
The SharedWorker works very slightly differently when it comes
to communication. For starters there's the concept of ports—this
is an array-like object that contains a reference to each of the
communication channels the shared worker has. Also, if you
bind to the message event using addEventListener , you have
to manually start the worker, which I'll show you in the following
code sample.
In addition, within the worker the connect event fi res when the
SharedWorker is created, which can be used to keep track of
how many connections the worker has to other documents.
The documents creating the SharedWorker contain the
following code:
var worker = new SharedWorker('messages.js');
worker.port.addEventListener('message', function(event) {
var messages = JSON.parse(event.data);
showNewMessages(messages);
}, false);
worker.port.start();
In the previous example, you can see we're accessing the
worker via the port property. This is how you interact and, in
fact, distinguish between shared and nonshared workers. As the
example binds to the message event using addEventListener ,
the worker must be connected manually using the .start()
 
Search WWH ::




Custom Search