Last active
October 3, 2016 10:12
-
-
Save saginadir/db45bb65b7966202b50bbdb9fe088ffc to your computer and use it in GitHub Desktop.
Inline Web Worker, from XHR or string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.