Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
<!DOCTYPE html>
<title>Workers: Compatibility</title>
// This script is executed in the main window
we'll use a worker to filter a huge data set
for all entries that match our filter string "foo"
var worker = new Worker('worker-javascript-file-2.js'),
message = {
fn: 'filterHugeDataSet',
data: {
faa: 'bar',
fee: 'ber',
fii: 'bir',
foo: 'bor',
fuu: 'bur'
filter: 'foo'
For this to work the same way in both Gecko and WebKit,
we'll need to stringify the object before sending it
Now it looks like this:
When the worker has filtered the data and returns it
to our application's main window thread,
we'll need to translate it back into an object manually
worker.addEventListener('message', function (event) {
var filtered = JSON.parse(;
// remember, we put our results in the data property of the filtered object inside the worker
}, false);
// This script is executed in the worker
The worker will begin running when it receives
a message from the main window.
The first thing it will have to do is parse the
message back into object.
var filters = {
filterHugeDataSet: function (data, filter) {
// do some kind of filtering...
// this is crummy, but you get the idea
var obj = {};
for ( var key in data ) {
if ( key == filter ) {
obj[key] = data[key];
return obj;
self.addEventListener('message', function (event) {
var message = JSON.parse(,
filtered = {};
`message` is now an object again. and looks how
you expect it to:
message = {
fn: 'filterHugeDataSet',
data: { foo:'bar' },
filter: 'foo'
Use your imagination here...If we had an object
called "filters" with a function property called
"filterHugeDataSet" we could now call it with
the params we passed along with the data
filtered['data'] = filters[message.fn](, message.filter);
Now we want to send it back. Once again we'll
manually serialize the object
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment