Monday, July 27th, 2009

Adding your own scripts to Web Workers

Category: JavaScript

<>p>Over in Geneva, they have posted on coupling PHP and Workers.

They build on the great intro from John and tweak it to use simple PHP on the backend to do things such as making sure that your favourite library has been loaded into each Worker, so you can use it in your script.

javascript
< view plain text >
  1. //  Recieve data FROM the client with postMessage()
  2. onmessage = function(event){
  3.   if ( event.data === 'load' ) {
  4.     postMessage( '-----BEGIN TRANSMISSION-----');
  5.     postMessage( {'server_objects': this} );
  6.  
  7.     $.ajax.get({
  8.       url: 'xhr_test_content.txt',
  9.       callback: function(response) {
  10.         var text = response.text;
  11.  
  12.         postMessage( 'AJAX GET RETURNED: ' + text );
  13.       }
  14.     });    
  15.     postMessage( '-----END TRANSMISSION-------');
  16.   }
  17. };

The Worker implementations are doing well these days. For awhile Safari didn’t have importScripts but that changed before Safari 4. Chrome had some weird side effects too recently, and Malte Ubl posted on some strangeness that we ran into with our Bespin Worker Facade.

We tested for:

javascript
< view plain text >
  1. if (typeof Worker == "undefined") {

But that didn't work. Malte explains:

For some reason the statement above is actually true in Chrome 2, even though as stated above support for the Worker API has not been implemented.

I then tried to instantiate the Worker object. All this does is to throw an exception with the message "Worker is not enabled". This looks like an unfinished implementation that was only partially removed or something in that direction.

This code handles the special case:

javascript
< view plain text >
  1. var noWorker = typeof Worker == "undefined" ? true : false;  
  2.  if(!noWorker) {  
  3.   try { new Worker("test.js") }  
  4.   catch(e) {  
  5.       e = e + ""  
  6.       if(e.indexOf("Worker is not enabled") != -1) {  
  7.           noWorker = true;  
  8.       }  
  9.   }  
  10. }

The bug is filed. The good news is that workers are looking pretty good these days!

Related Content:

Posted by Dion Almaer at 6:03 am
3 Comments

+++--
3.1 rating from 27 votes

3 Comments »

Comments feed TrackBack URI

It’s usually better to avoid double negatives. Also, true/false in that ternary is really redundant : )

var hasWorker = typeof Worker != “undefined”;
if (!hasWorker) { … }

Comment by kangax — July 27, 2009

I implemented web workers in Passpack 7 to speed up some jobs when Google Gears is not installed.
I simply check it with:

if (window.Worker) …

It works well with all browsers.

Comment by Sullof — July 27, 2009

Leave a comment

You must be logged in to post a comment.