HTML and CSS Reference
Figure 5-7. The message log
The controlWorker.js file contains three functions that provide the implementation for the three buttons
on the form. It first declares a myWorker variable, which holds a reference to the dedicated web worker.
createWorker() - This function first checks to see if the browser supports web workers by
seeing if the Worker class is defined. If not, an alert is raised. It then creates an instance of
the Worker class saving its reference in the myWorker variable. The worker implementation
is passed to its constructor by referencing the worker.js script file. It then creates the
onmessage event handler that adds the incoming message to the output field.
sendWorkerMessage() - This simply calls the worker's postMessage() method passing in
the text specified in the message field. Notice it is using the querySelector() method that
I explained earlier in this chapter.
closeWorker() - This calls the worker's terminate() method and sets the myWorker
variable to null. The worker is closed immediately without any ability to perform any
■ Tip in the same way that you added an onmessage event handler you can also create an onerror event
handler to respond to errors from the worker.
With this simple implementation you can see how easy it is to create a worker and use messages to
communicate with it.
Creating a Shared Worker
A shared web worker allows you to create a worker and then reuse it from other pages. There are a couple of
advantages to using shared workers. The most obvious one is that multiple pages can share the same thread
instead of having to create a new worker thread for every page. The other, which I'll explain later, is to share state
information across pages.
the same but the communication is done a little differently. You'll add a few more buttons to the web page and