Skip To Main Content

Expanding Capabilities of Javascript Web Workers

Posted by Rick Waldron

Jul 26 2009

Yesterday, I was introduced to Javascript Web Workers during a bad-ass FireBug console hack-session with Al MacDonald (http://hyper-metrix.com). I have to say… this is the coolest thing I’ve seen in a very long time… Workers are currently available in FireFox 3.5, Safari 4 and (according to John Resig) the Chromium Nightlies.

I’d like to consider this article more of an “advanced” web workers topic, so I’ll skip the explanation of the basic introduction to web workers and simply give you the files to begin with: download workers-simple.zip

Unzip this and drop it into your locahost. Open all the files and review them. If you want more information about what you’re looking at, have a gander at this. If you’re ready to really kick out the jam, then keep reading.

You might have already been saying to yourself “what the hell can I do with this in the real world?” and the answer is not much – except for reporting the current time over and over again. So let’s turbo-charge this worker.

First things first… scripts called by the Worker object do have XMLHttpRequest, but who wants to copy/paste or rewrite their XHR methods into EVERY worker script? Not me, that’s for sure. But now we’re faced with the challenge of getting external files into our worker script. This part is shockingly simple. Ready? GO!

  1. Open index.php:
    • Line 9, replace:
      var worker = new Worker('worker.js');
      
      …with…
      var worker = new Worker('worker.js.php');
      
    • Line 14, add:
      $(document).ready(function () {
        $('#post')
          .click(function () {
            worker.postMessage('load');
          });
      });
      
  2. Open worker.js and at the top of the file, add this:
    
    
  3. Now, save-as “worker.js.php”.

Great! Now let’s add a small ajax library… (get that here)

  1. In worker.js.php, add an include to ajax.js below the header() call, it will look like this:
    
    
  2. At the bottom of the script, add in the following:
    //  Recieve data FROM the client with postMessage()
    onmessage = function(event){
      if ( event.data === 'load' ) {
        postMessage( '-----BEGIN TRANSMISSION-----');
        postMessage( {'server_objects': this} );
    
        $.ajax.get({
          url: 'xhr_test_content.txt',
          callback: function(response) {
            var text = response.text;
    
            postMessage( 'AJAX GET RETURNED: ' + text );
          }
        });
        postMessage( '-----END TRANSMISSION-------');
      }
    };
    

Back to index.php…

  1. Inside the body, add this: >input type=button id=”post” value=”post back to server”<

Create a new file called “xhr_test_content.txt” And put whatever you want in it (or… challenge yourself and make it a PHP file that gets some kind of data from a db… )

Lastly… open your new index.php file in FireFox 3.5, fire up the console and let it rip. Click your new button to see what it returns.

If I missed something in my steps, you can always download the finished the code and run it yourself in its complete form. Download Completed Source Here

Check out the demos: Simple Waycool

Comments

We moved off of Disqus for data privacy and consent concerns, and are currently searching for a new commenting tool.

Contact Us

We'd love to hear from you. Get in touch!