Last active
December 16, 2015 13:59
-
-
Save pfrazee/5445437 to your computer and use it in GitHub Desktop.
trying to add `require()` to Web Workers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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