Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Web Workers into a Module build with Requirejs?

I have a well working app writing with Requirejs and Backbonejs, but it's really slowing sometimes... For example when it comes to make some arithmetic work! I tried to use a Web Worker to do this arithmetic work like this :

My Module(traffic.js) :

define(["jquery", "use!underscore", "use!backbone", "namespace" ],
  function ($, _, Backbone, globals) {
    .....  
    var worker = new Worker("arithmetic.js");
    worker.addEventListener('message', function(e) {
         console.log(e.data);
    }, false);

    worker.postMessage(globals.data); // Send data to our worker.
  });

arithmetic.js :

define(["use!underscore", "use!backbone" ],
  function ($, _) { 
      //Here die Operations
 });

But i have the Error define is not defined!!

I tried it like this too but no success!!

How to use Web Worker into requirejs or with backbonejs??

Thanks!

like image 745
3logy Avatar asked Feb 11 '12 23:02

3logy


1 Answers

You can use requireJS from web workers: see the API docs for more info.

The only requirement is to load requireJS at the start of the web worker with importScripts(…). Once that is loaded, you can use define and use requireJS like normal.

The key part for me when I was getting it to work was to make sure that you are also loading the same bootstrap configuration (e.g. config.js or main.js) in the web worker that you are using in the rest of your app. This is what the doc is talking about when it says:

You will likely need to set the baseUrl configuration option to make sure require() can find the scripts to load.

Another thing is that you can load the worker from your traffic.js file with a module ID (instead of hardcoding the script path) utilizing this requireJS plugin.

like image 163
Chad Avatar answered Oct 21 '22 20:10

Chad