Skip to content

Instantly share code, notes, and snippets.

@loganpowell
Last active May 7, 2023 19:55
Show Gist options
  • Select an option

  • Save loganpowell/fabc7ec7fcda56865a471ff73fae4842 to your computer and use it in GitHub Desktop.

Select an option

Save loganpowell/fabc7ec7fcda56865a471ff73fae4842 to your computer and use it in GitHub Desktop.
Using RequireJS in Web Worker
// See documentation: https://requirejs.org/docs/api.html#webworker
// working example: https://jsfiddle.net/yojaar80/2/
// from SO: https://stackoverflow.com/questions/36840329/whats-the-right-way-to-use-require-js-with-web-workers
importScripts("require.js");
requirejs.config({
//Lib path
baseUrl: '.',
// Some specific paths or alternative CDN's
paths: {
"socket.io": [
"//cdn.socket.io/socket.io-1.3.7",
"socket.io.backup"]
},
waitSeconds: 20
});
requirejs(["LibName"], (TheLibrary) = > {
// code after all is loaded
self.onmessage = (msg)=>{
// do stuff
TheLibrary.doStuff(msg.data);
}
// I tend to dispatch some message here
self.postMessage("worker_loaded");
}
/* Note that it is only after you receive "worker_loaded" that you can
post messages to the worker, because only then the message will be accepted.
Before, the onmessage callback is not yet estabilished.
So your main code should look: */
var worker = new Worker("myworker.js");
worker.onmessage = function(e) {
if(e.data=="worker_loaded") {
// Tell worker to do some stuff
}
}
// Example from: http://ruslanas.wri.lt/requirejs-in-web-worker/
// worker.js
importScripts('require.js');
require(['module'], function(dep) {
postMessage('module loaded');
onmessage = function(msg) {
// do cool stuff
postMessage('done');
}
});
// script.js
var worker = new Worker('worker.js');
// following message will not be heard
worker.postMessage('listening');
worker.onmessage = function(e) {
switch(e.data) {
case 'module loaded':
worker.postMessage('data');
break;
case 'done':
// update GUI
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment