HTML and CSS Reference
In-Depth Information
Figure 5-9.
Displaying the Task Manager
Now let's look at how the shared worker was implemented. Just like the dedicated worker, it must handle the
onconnect
and
onmessage
events. However you can't attach the
ommessage
handler directly to the worker; instead
you must access a port and attach to that. The
onconnect
event receives an
event
parameter and you access
the port by
event.ports[0]
. Once you have the
port
you can attach the event handler to it. You use the port's
addEventHandler()
method. This takes two parameters. The first is the name of the event,
message
in this case.
The second parameter is the function that will be called when the event is raised.
When sending a message back you must also use the
port
object. This port object is provided in the
event.
target
property of the incoming message. Both this event handler and the
onconnect
event handler use the
sendResponse()
function passing in the port object.
The functions in the
controlSharedWorker.js
file are almost identical to their dedicated counterparts.
However, they must also use the port object.
Notice in the
sharedWorker.js
file that the
clients
variable is declared and then incremented in the
onconnect
event handler. This is used to keep track of how many clients have connected to the shared worker.
I added this just to demonstrate how this variable is global to all the clients attached to the worker. In fact, there is
no per-port instance data; all data is global.
Also, when a message comes in, the
event
parameter includes the
port
that the response should be sent
to. The worker doesn't “remember” the
port
for each client. It just does what it's instructed to do and returns a
response on the specified
port
.
Using Visual Studio Bundling and Minification
When a browser loads a page, all of the referenced files such as style sheets and JavaScripts must be loaded as
well. Each file is retrieved from the server with an HTTP request, so a separate round-trip is required for each file.
Also, while we like white space and comments to make our code more manageable, this is extra data that must
be downloaded but ignored by the browser. If you're concerned about your page loading faster, there are two
techniques that can make a big difference.
•
Bundling -
Bundling
is the process of taking all the individual files and concatenating
them into a single file. This will reduce the amount of server round-trips it will take to
load your page.