Skip to content

Instantly share code, notes, and snippets.

@pfrazee
Last active December 16, 2015 13:59
Show Gist options
  • Save pfrazee/5445437 to your computer and use it in GitHub Desktop.
Save pfrazee/5445437 to your computer and use it in GitHub Desktop.
trying to add `require()` to Web Workers
// this works, but the imported scripts pollute the global namespace
function require(url) {
self.module = { exports:{} };
importScripts(url);
var exports = self.module.exports;
delete self.module;
return exports;
};
// this is the one I want:
function require(url) {
var timeout = 15 * 1000; // 15s for now
var promise = local.http.dispatch({ method:'get', url:url });
var startTime = (new Date()).getTime();
while (promise.isUnfulfilled() && ((new Date()).getTime() - startTime) < timeout) {
// :TODO: let message queue drain?
}
if (promise.isFulfilled()) {
var res = promise.value;
if (/javascript/.test(res.headers['content-type']) || /\.js$/.test(url)) {
var module = { exports:{} };
importScripts(makeJSDataURI('(function(){ ' + dataUrl + ' })();'));
return module.exports;
} else
return res.body;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment