HTML5 Web Workers usually depend on external scripts using importScripts()
. Where should such scripts go under Rails 4, so that they get minified normally as per the assets pipeline, and yet still work correctly?
There are some problems when working with the asset pipeline that need to be addressed:
vendor/assets
, are not processed by the asset pipeline by default (which wasn't the case in Rails 3).app/assets
, they need to be included in application.js
in order to be processed. However, worker files should not be included in the combined output (i.e. application-[digest].js
).new Worker('myWorker.js')
. How would we find out the path? (I tried asset_path
, but it didn't work).importScripts()
. How would we find out the path to load?For anyone coming here from Google - you can use Inline Workers.
Inline Workers
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:
var blob = new Blob([
"onmessage = function(e) { postMessage('msg from worker'); }"]);
// Obtain a blob URL reference to our worker 'file'.
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
worker.onmessage = function(e) {
// e.data == 'msg from worker'
};
worker.postMessage(); // Start the worker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With