Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created May 18, 2010 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rwaldron/405572 to your computer and use it in GitHub Desktop.
Save rwaldron/405572 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Workers: Compatibility</title>
<script>
// 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:
"{"fn":"filterHugeDataSet","data":{"faa":"bar","fee":"ber","fii":"bir","foo":"bor","fuu":"bur"},"filter":"foo"}"
*/
worker.postMessage(JSON.stringify(message));
/*
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(event.data);
// remember, we put our results in the data property of the filtered object inside the worker
console.log(filtered.data);
}, false);
</script>
</head>
<body>
</body>
</html>
// 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(event.data),
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.data, message.filter);
/*
Now we want to send it back. Once again we'll
manually serialize the object
*/
this.postMessage(JSON.stringify(filtered));
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment