You can use require with Workers. In your working script you need to call
self.importScripts('../path/require.js');
At the request of the documents, you can transfer the configuration object to the module:
requirejs.config({ //By default load any module IDs from js/lib baseUrl: 'js/lib', //except, if the module ID starts with "app", //load it from the js/app directory. paths //config is relative to the baseUrl, and //never includes a ".js" extension since //the paths config could be for a directory. paths: { app: '../app' } }); // Start the main app logic. requirejs(['jquery', 'canvas', 'app/sub'], function ($, canvas, sub) { //jQuery, canvas and the app/sub module are all //loaded and can be used here now. });
Combination
worker.js
self.importScripts('../path/require.js'); requirejs.config({ //By default load any module IDs from path/lib baseUrl: 'path/lib', //except, if the module ID starts with "app", //load it from the js/app directory. paths //config is relative to the baseUrl, and //never includes a ".js" extension since //the paths config could be for a directory. paths: { app: '../app' } }); // Start the main app logic. requirejs(['jquery', 'canvas', 'app/sub'], function ($, canvas, sub) { //jQuery, canvas and the app/sub module are all //loaded and can be used here now. // now you can post a message back to your callee script to let it know require has loaded self.postMessage("initialized"); }); self.onmessage = function(message) { // do cpu intensive work here, this example is not cpu intensive... if(message.data === 'to process') { self.postMessage("completed!"); } }
Node Work Challenge
var worker = new Worker('Worker.js'); worker.onmessage = function(event) { var msg = event.data; if(msg === 'initialized') { worker.postMessage({data: 'to process'}); } }
source share