Skip to content

Instantly share code, notes, and snippets.

@saginadir
Last active October 3, 2016 10:12
Show Gist options
  • Save saginadir/db45bb65b7966202b50bbdb9fe088ffc to your computer and use it in GitHub Desktop.
Save saginadir/db45bb65b7966202b50bbdb9fe088ffc to your computer and use it in GitHub Desktop.
Inline Web Worker, from XHR or string
let inlineJs = `function(){ console.log("Some JS Code!") }`;
let workerBlob = window.URL.createObjectURL(new Blob([inlineJs]));
let worker = new Worker(workerBlob);
/**
* XHR with worker
*/
let worker; // Keep this in the global scope
var request = new XMLHttpRequest();
request.open('GET', '/js/my_worker_code.js', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
let inlineJs = request.responseText;
let workerBlob = window.URL.createObjectURL(new Blob([inlineJs]));
worker = new Worker(workerBlob);
} else {
}
};
request.send();
@saginadir
Copy link
Author

Sometimes we want to create a worker to run functionality not on the main thread, inline workers are possible using the techniques above.

Using an Ajax request to require the web worker.js file will help to ease the load and call the functionality only when needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment