Web workers without a separate Javascript file?
http://www.html5rocks.com/en/tutorials/workers/basics/#toc-inlineworkers
What if you want to create your worker script on the fly, or create a self-contained page without having to create separate worker files? With Blob(), you can "inline" your worker in the same HTML file as your main logic by creating a URL handle to the worker code as a string
Full example of BLOB inline worker:
<!DOCTYPE html>
<script id="worker1" type="javascript/worker">
// This script won't be parsed by JS engines because its type is javascript/worker.
self.onmessage = function(e) {
self.postMessage('msg from worker');
};
// Rest of your worker code goes here.
</script>
<script>
var blob = new Blob([
document.querySelector('#worker1').textContent
], { type: "text/javascript" })
// Note: window.webkitURL.createObjectURL() in Chrome 10+.
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
console.log("Received: " + e.data);
}
worker.postMessage("hello"); // Start the worker.
</script>
Make a function run via web workers
You can inline a web worker as a blob without using a separate file:
<script id="worker1" type="javascript/worker">
// This script won't be parsed by JS engines because its type is javascript/worker.
self.onmessage = function(e){
self.postMessage('msg from worker');
};
// Rest of your worker code goes here.
</script>
<script>
var blob = new Blob([ document.querySelector('#worker1').textContent ], { type: "text/javascript" });
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
console.log("Received: " + e.data);
}
worker.postMessage("hello");
// Start the worker
</script>
Note that browser support might not be as robust with this method.
See here for additional details: https://stackoverflow.com/a/6454685/5535081
Related Topics
Accessing Private Member Variables from Prototype-Defined Functions
How to Get the Function Name from Within That Function
How to Call Reduce on an Array of Objects to Sum Their Properties
Looping Through an Object (Tree) Recursively
Detect Back Button Click in Browser
Jquery Ajax Call to PHP Script with JSON Return
How to Sort Elements by Numerical Value of Data Attribute
Adding Multiple Event Listeners to One Element
How to Use JavaScript to Dynamically Change a Video's Source
JavaScript Filter Array Multiple Conditions
How to Split the Ng-Repeat Data with Three Columns Using Bootstrap
How to Tell If Caps Lock Is on Using JavaScript
How to Make JavaScript Object Using a Variable String to Define the Class Name
Can JavaScript Connect with MySQL
Webhoster Inserts a JavaScript Which Brokes My Code How to Remove It