GithubHelp home page GithubHelp logo

angular-workers's Introduction

angular-workers

A wrapper for web workers in angular

###Why?

Using web workers is somewhat awkward in raw Javascript. Doing it in angular applications even more so. Each web worker runs in it's own context, and this context is isolated from the angular application.

###What does angular-workers do angular-workers provides an angular service which upon request creates a web worker. The returned web worker runs it's own angular context which allows it to resolve angular dependencies.

Mor information about how angular-worker work can be found in this blog post.

##Installation

install with bower using:

bower install angular-workers

##How to use

  • Depend on the WorkerService.

  • Specify the URL to the file containing the angular script by invoking:

    // The URL must be absolute because of the URL blob specification  
    WorkerService.setAngularUrl(url)
  • OPTIONALLY: Specify how the web worker is to find any dependencies by invoking:

    // The URL must be absolute because of the URL blob specification  
    WorkerService.addDependency(serviceName, moduleName, url) 
  • Create create a promise of an angularWorker by invoking:

    var workerPromise = WorkerService.createAngularWorker(['input', 'output' /*additional optional deps*/,   
        function(input, output /*additional optional deps*/) {  
            // This contains the worker body.
            // The function must be self contained. The function body will be 
            // converted to source and passed to the worker.  
            // The input parameter is what will be passed to the worker when
            // it is executed. It must be a serializable object.
            // The output parameter is a promise and is what the 
            // worker will return to the main thread.  
            // All communication from the worker to the main thread is performed
            // by resolving, rejecting or notifying the output promise.
            // We may optionally depend on other angular services. 
            // These services can be used just as in the main thread. 
            // But be aware that no state changes in the angular services in the
            // worker are propagates to the main thread. Workers run in fully isolated
            // contexts. All communication must be performed through the output parameter.
      }]);
      ```
  • When the workerPromise resolves the worker is initialized with it's own angular context and is ready to use. Like so:

    workerPromise.then(function success(angularWorker) {  
        //The input must be serializable  
        return angularWorker.run(inputObject);    
      }, function error(reason) {  
        //for some reason the worker failed to initialize  
        //not all browsers support the HTML5 tech that is required, see below.  
      }).then(function success(result) {  
        //handle result  
      }, function error(reason) {  
        //handle error  
      }, function notify(update) {  
        //handle update  
      });
      ```

The same initialized worker can be used many times with different input.

##Requirements

The browser running the angular service needs to support the following:

##Limitations

The angular-workers is a wrapper around standard web workers. So all limitations with web workers apply.

  • Data sent between the worker and main thread is deep cloned. (angular-workers does not use transferable objects, yet) This means transferring large object (about >20Mb, Communicating Large Objects with Web Workers in javascript, Samuel Mendenhall) will cause noticeable delays. Samuel Mendenhall recommends sending the data in chunks. This can be achieved using the notify in the angular promise.
  • There is no DOM in the worker. Other things are missing as well. No global "document" object. The bare minimum of these have been mocked to allow angular to start in the worker.
  • The web worker share no runtime data with the main thread. This is great since it prevents deadlock, starvation and many other concurrency issues. But it also means that any angular service instance upon which your worker depends is created in that worker, and not shared with the main thread. One can not communicate data between worker and main thread by using service states. All communication must be done through the input object and output promise.
  • Running in a separate context means the web worker does not share the cookies set in the main thread! If you depend on cookies for authentication pass these manually to the worker.

angular-workers's People

Contributors

dennieru avatar fredriksandell avatar hirohitokato avatar jaimechavarriaga avatar kityan avatar pelirrojo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-workers's Issues

Communication?

Do i understand correctly: it is not possible to communicatie through postMessage()? Is there an other way for the worker to communicate with the application after the worker has been initialized?

Uncaught TypeError: Cannot read property 'prototype' of undefined

Is anyone else getting this error?

I am just trying to create a very simple web worker but I can't get past this error.

When I do some debugging, I see I am getting an initialization error with this reason...

message { target: Worker, isTrusted: true, data: "{}", origin: "", lastEventId: "", ports: MessagePortList, eventPhase: 0, bubbles: false, cancelable: false, defaultPrevented: false, timeStamp: 1465518268434703 }

does anyone know what this is and why its an error?

Thanks in advance!

Relative path to host base instead of absolute url

Hi Fredrik,

Your module is just awesome !

Why you don't detect relative path and suffix it thanks to the $location service ?

$location.protocol() + '://' + $location.host() + ':' + $location.port() + '/'

Related to :

// The URL must be absolute because of the URL blob specification  
WorkerService.setAngularUrl(url)

provide simple example of addDependency

How is one supposed to use addDependency to include external libraries? Consider this example:

  • I need to include lodash into my WW
  • I create a service that returns the lodash object:
angular.module('ext.lodash', []).factory('_', function() {
    // WWs don't have access to 'window', will it affect this return value?
    return window._;
});
  • I use addDependency and expect it to be injected:
WorkerService.addDependency('_', 'ext.lodash', 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js');

This later results in an DI error when calling createAngularWorker. What am I doing wrong? I consider adding external libraries one of the most important feature since they allow me to include relevant math and utility libraries.

npm module request

I was wondering if you would be able to create an npm package for this. Thanks for the great abstraction!

Uncaught SecurityError: Failed to construct 'Worker'

Hi I'm trying to replicate the example. But I got this error.

angular-workers.min.js:1 Uncaught SecurityError: Failed to construct 'Worker': Access to the script at 'blob:http%3A//localhost%3A8100/9509abbd-fe00-425a-9053-de3018be6f69' is denied by the document's Content Security Policy.

Concurrency problem

Hi, I'm currently trying to re-use the angular-worker and I already managed to only execute the Run function once the angularWorker is finally available, the problem is, when multiple executions run concurrently, the response from the worker get mixed up. I'm currently only returning a $http request from the worker

return $http({ method: input.method, url: input.url, data: input.data, headers: input.headers, config: input.config }).then(function (result) { output.resolve(JSON.parse(JSON.stringify(result))); }, function (fail) { return output.reject(fail); });

When running the same code but always creating a new worker, it works like a charm since there is no possible way to 1 request get mixed up with another worker job.

Using with Browserify

I am currently trying to do exactly what this service does!....
BUT! I am using browserify. So the URL's don't really work. I have also been looking at WebWorkify
https://github.com/substack/webworkify

Basically I need a combination of the two tools. Do you have any tips on achieving this?

I am considering changing the .addDependency function to take a function argument, which could be used to do something like .addDependency(require('./utils/service.js')). The function would then be stringified instead of created into an include script statement. Is this a good approach?

cannot use $sce.trustAsHtml

problems with angular 1.5

hello, there seems to be a problem with angular 1.5

WorkerService.setAngularUrl('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js');

causes

Script error.

as far as I can tell this happens with every version after 1.4.7

Question: Is it possible?

Question:

I am a bit new to web workers, so maybe this is a stupid question.

I would like to use web worker when angularjs is creating html of data. I have a table, and I use ngRepeat=”tableData”, is it possible to use this lib, for when tableData changes, that processing and appending of the table is done in a web worker?

Is that even possible to do with web workers?

How to Reuse or Destroy a Worker Thread

Firstly, thanks for this great module, it is working well. I am successfully using it to retrieve comments over $http.

My only issue is that It appears to be spawning a new thread every time I request the comments for a different node (different url value in $http request) in my app . See image below from Chrome Inspector:

image

Question:

  1. How would I reuse an existing worker? A code example would be great.
  2. How do I destroy a worker?
  3. Is this a problem? Does the browser care if many idle threads are spawned?

My Code Partial

var workerPromise = WorkerService.createAngularWorker(['input', 'output', '$http', 
                function(input, output, $http) {
                    var XSRFToken = input.XSRFToken;
                    var url = input.url;
                    var commentsModel = $http({
                        method: "get",
                        url: url,
                        headers : { 'X-XSRF-TOKEN' : XSRFToken }
                    });
                    commentsModel.then(function(response) {                        
                        output.resolve(response.data);                       
                    }, function(error) {                        
                        output.reject(error);                       
                    });
                }
            ]);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.