padolsey / operative

:dog2: Seamlessly create Web Workers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

importScripts support

evanworley opened this issue · comments

Have you considered a way to allow the worker to importScripts? I have a few ideas for how it might be done.

  1. Add a second argument to the constructor with an array of URLs
operative({
  method1: function() {}
}, ["http://myhost.com/scripts/importlib-0.0.1.js"])
  1. Add a special property to the object passed during construction
operative({
    method1: function() {},
    __scripts__: ["http://myhost.com/scripts/importlib-0.0.1.js"]
})

This way these scripts could be loaded for all methods of the worker. Also when degrading back to running in the UI thread, you could either just ignore these scripts, or only load them if they are not already present on the page.

Thoughts?
Evan

In case it wasn't clear in the original request, this is to save the developer from having to check if we have a document and/or import scripts is defined. It also saves the developer from having to import the same script in all of the worker methods (if the script is needed by all of them).

This feature is a must!

As a part of this, I'm also looking to use an IFRAME to run an operative when Workers are not supported. This way we're not loading anything in the same scope as the parent page.

I'm a fan of the first option, passing an array of dependencies.

This'll have to go into 0.2.0.

I think using an iframe is a great idea, and a sandboxed iframe where supported. I can help with this feature if you like.

So if your curious the way this is dealt with in communist is to use regexes to grab any import script declarations, dedup them and then if it's a real worker, hoist them up to the global worker scope, or if it's a fake worker download them as text and eval them with the rest of the fake worker script while also putting a hold on any calls so that calls to the fake worker that come before the scripts download aren't evaluated until after the scripts all download.

Sorry, didn't mean to close the issue :/

Chose the former pattern of operative(meth, dependencies). 0.2.0 has been merged. So this feature is now in:

// Create interface to call lodash methods inside a worker:
var lodashWorker = operative(function(method, args, cb) {
    cb(
        _[method].apply(_, args)
    );
}, [
    'http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.3.1/lodash.min.js'
]);

lodashWorker('uniq', [[1, 2, 3, 3, 2, 1, 4, 3, 2]], function(output) {
    output; // => [1, 2, 3, 4]
});

Well, at least it's readable =)

Nice!