This is the bocoup web log with posts from Al, Boaz, Rick, Sam, Nate, Nick & Pete. You should also make sure to checkout code.bocoup.com, where we keep the finished versions of ideas we kick around here.


Jul 26, 2009

Expanding Capabilities of Javascript Web Workers

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:
      1
      
      var worker = new Worker('worker.js');

      …with…

      1
      
      var worker = new Worker('worker.js.php');
    • Line 14, add:
      1
      2
      3
      4
      5
      6
      
      $(document).ready(function () {
        $('#post')
          .click(function () {
            worker.postMessage('load');
          });
      });
  2. Open worker.js and at the top of the file, add this:
    1
    2
    3
    
    <?php
    header('Content-type: text/javascript');
    ?>
  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:
    1
    2
    3
    4
    
    <?php
    header('Content-type: text/javascript');
    include('ajax.js');
    ?>
  2. At the bottom of the script, add in the following:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    //  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:
    1
    
    <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:

4 Comments

  1. Posted July 26, 2009 at 7:07 pm | Permalink

    Shouldn’t this also work with Safari 4? If so, why limit to just Firefox 3.5?

  2. Posted July 26, 2009 at 7:54 pm | Permalink

    not sure i understand why this is way cool, its simply some dynamically created scripts, and some post messages…

    pretty standard stuff really.

    i gotta admit, once i began working on web workers, i did share the same initial response tho….

    WAY COOL! :)

  3. Rick Waldron
    Posted July 27, 2009 at 8:50 am | Permalink

    @GG

    I think it’s way cool.

    1. There are no dynamically created scripts.
    2. postMessage() is a method of the Worker object, which only debuted as part of HTML5 and then was broken off into it’s own specification.
    3. It still remains… WAY COOL :D

  4. Posted July 27, 2009 at 12:56 pm | Permalink

    Keep in mind that importScripts() exists… This example is to show instead how it can be compiled into one file. The method shown here has security advantages.

10 Trackbacks

  1. [...] Over in Geneva, they have posted on coupling PHP and Workers. [...]

  2. [...] Over in Geneva, they have posted on coupling PHP and Workers. [...]

  3. [...] Over in Geneva, they have posted on coupling PHP and Workers. [...]

  4. By Adding your own scripts to Web Workers on July 28, 2009 at 12:37 pm

    [...] Over in Geneva, they have posted on coupling PHP and Workers. [...]

  5. By Menambahkan script sendiri ke Web Workers on August 4, 2009 at 11:08 am

    [...] GenevaJS [...]

  6. [...] Over in Geneva, they have posted on coupling PHP and Workers. [...]

  7. [...] Over in Geneva, they have posted on coupling PHP and Workers. [...]

  8. By Experimenting with web workers | NCZOnline on August 18, 2009 at 9:00 am

    [...] the past couple of months, there’s been some good information floating around about web workers. I have no desire to add yet another introduction to the topic into the [...]

  9. By Expanding Capabilities of Javascript Web Workers on September 1, 2009 at 8:03 am

    [...] link: Expanding Capabilities of Javascript Web Workers Share and [...]

  10. By PollenJS: Javascript Web Workers Library on September 14, 2009 at 5:31 pm

    [...] a follow up to my previous post regarding Javascript Web Workers, I’m pleased to announce the release of PollenJS, the first worker-specific javascript [...]




Please send your questions to this address or call Bocoup at 617-379-2752
This web page is proudly maintained by Bocoup and hosted by (mt) Media Temple
All code on this website is Open Source