Architect.js, Polyfill and Manage Web Workers

Architect.js, polyfill and manage web workers

Architect.js is a wrapper for web workers that help to polyfill and manage the web worker. Architect.js has provided two type of workers: Short-lived workers and Long-lived workers. Both type of workers will have 3 basic workers provided: proxy, ajax and jsonp. By using web workers, it will benefit on heavy DOM manipulation and move some low priority process to background, to speed up your javascript process, especially on mobile devices.

Let’s take a look on two different type or workers.

Short-lived workers

These will be automatically terminated as soon as the work is done. It will spawn a new worker every time.

As stated official, when every time the Architect receive data, it will create a new web worker to process with.

Proxy

Architect.work(data, 'proxy', callback)

Ajax

Architect.work(url, 'ajax', callback).

JSONP

Architect.work(url, 'jsonp', callback).

Long-lived workers

These need to be manually terminated when the work is done. The same worker can therefore be reused many times with different data.

Different with Short-lived workers, it can be reused until you kill them. For this type of workers, it has better in controlling memory that not crash your app on runtime. You can define a jobName for the workers, so you can assign jobs to workers by using the jobName

Proxy

Architect.workOn(jobName, data, 'proxy', callback)

Ajax

Architect.workOn(jobName, url, 'ajax', callback)

JSONP

Architect.workOn(jobName, url, 'jsonp', callback)

Custom Worker

Architect.js allow us to write our own workers. Since Architect.js will polyfill the web worker to support old browsers, a fallback functions have to repeat on your main program, still is know too flexible here.

First, you have to create a worker javascript, let’s say custom-worker.js

// custom-worker.js
var name = 'worker-awesome';

function workerSign(e) {
    data = e.data;
    data.__sign = name;
    postMessage(data);
}

addEventListener('message', workerSign);

And you have to copy the function in worker to you main application.

// application.js

// clone the function from custom-worker.js
var name = 'worker-awesome';

function workerSign(data) {
    data.__sign = name;
    return data;
}

Architect.workFrom('custom-worker.js', 'foo', workerSign, function(data) {
    console.log(data)
})

Architect.js then will polyfill for old browser to make it works, you no need to handle them.

Check it out

Related Articles