HTML and CSS Reference
In-Depth Information
What about sending more than strings?
In the examples I've shown you so far, I've only passed strings
in messages back and forth. What about if you want to send
more than just a string? What if you have an object with proper-
ties and values?
Well, the good news is the specifi cation describes what's sup-
posed to happen when a browser has to safely send data from
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 property.
In fact, we saw this before in Chapter 6, “Data Storage,” where
we try to store objects in localStorage . So in the same way
as 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 sections on Web Workers and Web Sockets.
Threading using Web Workers
Web Workers are part of a separate specifi cation to the HTML5
spec, but 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 the worker runs in the background
without interfering with the main browser thread.
The browser is already responsible for requesting and parsing
fi fi e s , r e n d e r fi n g t h e v fi e w , a n d e x e c u t fi n g J a v a S c r fi p t , a n d a n y t h fi n g
that consumes the browser's processing time causes all other
jobs to wait. This is where Web Workers come to the rescue.
 
 
Search WWH ::




Custom Search