Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put a web worker file in Rails 4?

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:

  1. The external scripts, if placed under vendor/assets, are not processed by the asset pipeline by default (which wasn't the case in Rails 3).
  2. If the scripts are placed under 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).
  3. If the scripts are included into the assets config, then the resulting files would include a digest in their file name. To load the worker, one needs to give the browser its path (e.g. new Worker('myWorker.js'). How would we find out the path? (I tried asset_path, but it didn't work).
  4. Just like in 3, workers need to reference other files by name when calling importScripts(). How would we find out the path to load?
like image 677
Hosam Aly Avatar asked Dec 29 '14 23:12

Hosam Aly


1 Answers

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.
like image 142
learning_to_swim Avatar answered Oct 27 '22 08:10

learning_to_swim