HTML and CSS Reference
In-Depth Information
one source to another. It describes how to clone the data and
how it should be treated.
However, most browsers don't support this process. In fact,
most browsers simply coerce the object into a string. That sucks
for you and me. It means that instead of the nicely constructed
object, you'll get [object Object] in the event.data prop-
erty. In fact, we saw this before in Chapter 6, “Data Storage,”
where we try to store objects in localStorage . So in the same
way we got around the issue with localStorage , you can use
JSON.stringify to convert your JavaScript object into a string,
pass it to postMessage , and then, on the receiving side, convert
it back to a native JavaScript object using JSON.parse .
Using JSON.stringify and JSON.parse will be useful methods for
transferring more complicated objects from window to target,
as we'll see in the next section on Web Workers (and the next
chapter on WebSockets and Server-Sent Events).
Threading using Web Workers
Web Workers are part of a separate specification to the HTML5
spec, but they are a key feature in building web applications.
A worker is a way of running a discrete block of JavaScript in
a background process to the main browser. This is effectively
a thread. What this means is that the worker runs in the back-
ground without interfering with the main browser thread.
The browser is already responsible for requesting and parsing
files, rendering the view, and executing JavaScript, running the
UI/chrome, and anything that consumes the browser's process-
ing time causes all other jobs to wait. This is where Web Work-
ers come to the rescue.
Why use a worker?
If you've ever written any dodgy JavaScript that goes haywire,
causing your browser to start fuming like it's about to explode,
then you've experienced the single-threadedness of browsers.
Eventually, if the browser's smart, it'll give you the option to ter-
minate the dodgy code, something like Figure 10.1 .
 
 
Search WWH ::




Custom Search