Skip to content

Instantly share code, notes, and snippets.

@kishalmi
Last active August 29, 2015 13:55
Show Gist options
  • Save kishalmi/8734047 to your computer and use it in GitHub Desktop.
Save kishalmi/8734047 to your computer and use it in GitHub Desktop.
spawn a webworker without the need for a seperate file, including requirejs functionality
/*
assuming a rather standard requirejs script tag referring to main(.js)
<script type="text/javascript" data-main="main" src="js/require.min.js"></script>
*/
var w = newRequireWorker({
shim: { three: { exports: 'THREE' } },
baseUrl: 'js',
paths: { three: 'three.min' }
},
function () {
require(['three'], function () {
self.postMessage('rev: '+THREE.REVISION);
});
});
w.onmessage = function (e) {
console.log('msg from worker:', e.data);
};
// msg from worker: rev: 65
/**
* build a worker from an anonymous function body
* worker has requirejs loaded and configured (baseUrl at least)
* so require() is available.
*
* NOTE: can pass the main config like so:
* $.extend( requirejs.s.contexts._.config, {deps: null} )
* careful though, as these are requirejs internals and may change in the future! ;)
*
* @param {object} requirejsCfg
* @param {function} funcObj
* @param {string=} scriptPath - defaults to path of current file
* @param {string=} requirejsPath - defaults to path of requirejs script src
* @returns {Worker}
*/
function newRequireWorker(requirejsCfg, funcObj, scriptPath, requirejsPath) {
if (scriptPath === undefined) // make an educated guess about the absolute path of this script
scriptPath = document.location.href.substr(0, document.location.href.lastIndexOf('/') + 1);
if (requirejsPath === undefined) // load requirejs from 'src' of script tag with 'data-main' set
requirejsPath = $('script[data-main]').attr('src');
var src, cfg = $.extend(requirejsCfg, {baseUrl: scriptPath + (requirejsCfg.baseUrl || '')});
$.ajax({
url: requirejsPath,
async: false,
success: function (result) {
src = result
}
});
var blobURL = URL.createObjectURL(new Blob([
src,
'requirejs.config(' + JSON.stringify(cfg) + ');',
'(', funcObj.toString(), ')();'
], {type: 'application/javascript'})),
worker = new Worker(blobURL);
URL.revokeObjectURL(blobURL);
return worker;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment