[whatwg] Using Web Workers without external files

Jonas Sicking jonas at sicking.cc
Wed Sep 23 14:40:41 PDT 2009


On Wed, Sep 23, 2009 at 3:34 AM, Simon Pieters <simonp at opera.com> wrote:
> I'd like a way to use workers without having to use an external resource.
> This would allow easier testing, mashups, small standalone apps, and so
> forth.
>
> Possible ways to do it:
>
> * Support data: URLs in the constructor. A bit annoying to work with,
> though.
>     new Worker('data:...');
>     new SharedWorker('data:...', 'foo');
> * Point to an element within the same document with a fragment identifier.
>     <script type=text/x-worker id=worker>...</script>
>     new Worker('#worker');
>     new SharedWorker('#worker', 'foo');
> * Pass a string to the constructor with an additional parameter saying that
> it's a string of script rather than a URL.
>     new Worker('...', true);
>     new SharedWorker('...', 'foo', true);
> * Mint new constructors that you pass a string to instead of a URL.
>     new WorkerXYZ('...');
>     new SharedWorkerXYZ('...', 'foo');
> * ...other?
>
>
> Currently it seems it is possible to work around the external resource
> limitation by doing:
>
>    <!--
>    postMessage('works!');
>    /*
>    -->
>    <!doctype html>
>    <script>
>    // The empty string should work too, per spec, AFAICT, but
>    // Firefox and Chrome throw an exception for the empty string
>    var worker = new Worker('?');
>    worker.onmessage = function(e) { alert(e.data) }
>    </script>
>    <!--
>    */
>    //-->
>
> ...but this is a bit too hacky for my taste.

You can also work around it by doing something like this:

test.html:
<!DOCTYPE html>
<html>
<head><title>example</title>
<script>
str = "<script to evaluate>";
w = new Worker("externalStub.js");
w.postMessage(str);
</script>
</html>

externalStub.js:
onmessage = function(e) { eval(e.data); }

What's the use case? I think making data: urls is an ok solution,
unless the usecases are compelling enough that we think it's something
that people will do a lot.

/ Jonas


More information about the whatwg mailing list