JavaScript Wrapper for the HTML5 WebWorkers API

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

According to the WHATWG specifications, Web Workers allow for concurrent execution of the browser threads and one or more JavaScript threads running in the background. The browser which follows a single thread of execution will have to wait on JavaScript programs to finish executing before proceeding and this may take significant time which the programmer may like to hide from the user. It allows for the browser to continue with normal operation while running in the background.

Here’s a tiny JavaScript class for easy usage of the Workers API of HTML5. As of October 2012 Workers are supported by Firefox, Chrome, Opera, Safari and Internet Explorer 10. On older versions of IE, the class will not initialize.

After you have downloaded the class, please, make sure you check the comments in the script file to learn how to use the class.

So… Here we go:

The AcidJs.WebWorkers Class

[sourcecode language=”javascript”]
(function() {
    "use strict";

    /*
     * @namespace AcidJs
    **/
    if(undefined === window.AcidJs) {
        window.AcidJs = {};
    }

   /*
    * @class WebWorkers
    * @constructor
    * @author Martin Ivanov http://acidjs.wemakesites.net
    **/
    function WebWorkers() {
        if(typeof(window.Worker) === "undefined") {
            var
                fn = (function(){});

            for(var o in this) {
                if(Object.hasOwnProperty(o)) {
                    this[o] = fn;
                }
            }
        }
    }

    WebWorkers.prototype = {

       /*
        * @method create Create new WebWorker
        * @public
        * @param config {Object}
        * {
        *  name: {String},
        *  script: {URL},
        *  onMessage: {Function},
        * }
        **/
        create: function(config) {
            var
                name = config.name,
                script = config.script,
                onmessage = config.onMessage;

            if(undefined === config || undefined !== this[name]) {
                return;
            }

            this[name] = new Worker(script);
            this._bind(name, onmessage);
        },

       /*
        * @method getWorker Return Worker instance
        * @public
        * @param name {String}
        * @return XrayWrapper|undefined
        **/
        getWorker: function(config) {
            return this[config.name];
        },

       /*
        * @method start execute a Worker
        * @public
        * @param config {Object}
        * {
        *  name: {String}
        * }
        **/
        start: function(config) {
            var
                name = this.getWorker({name: config.name});

            if(undefined !== name) {
                name.postMessage(config.data);
            }
        },

       /*
        * @method stop terminate a Worker
        * @public
        * @param config {Object}
        * {
        *  name: {String}
        * }
        **/
        stop: function(config) {
            var
                name = this.getWorker({name: config.name});

            if(undefined !== name) {
                name.terminate();
            }
        },

       /*
        * @method destroy Stop and delete the instance of a Worker
        * @public
        * @param config {Object}
        * {
        *  name: {String}
        * }
        **/
        destroy: function(config) {
            var
                name = config.name;

            if(undefined !== this.getWorker({name: config.name})) {
                this.stop({
                    name: config.name
                });
                delete this[config.name];
            }
        },

       /*
        * @method _bind Attach handler to the onmessage event of the Worker
        * @private
        * @param name {String}
        * @onmessage {Function}
        * @data {Object|String}
        **/
        _bind: function(name, onmessage) {
            this[name].addEventListener("message", function(e) {
                onmessage.call(this, e.data);
            }, false);
        }
    };

    window.AcidJs.WebWorkers = WebWorkers;
})();
[/sourcecode]

Using the Class

[sourcecode language=”javascript”]
(function() {
    // instantiate the class
    window.workers = new AcidJs.WebWorkers();

    // create a worker
    window.workers.create({
        script: "AcidJs.WebWorkers/workers/process-guitars.js",
        name: "process-guitars",
        onMessage: function(data) {
            console.log(data);
        }
    });

    // start the worker, post a message to it and supply some data to be processed in the background
    window.workers.start({
        name: "process-guitars",
        data: ["schecter", "fender", "gibson", "jackson", "b.c. rich", "esp", "ibanez", "charvel"]
    });

    // get the worker
    // console.log(window.workers.getWorker({name: "process-guitars"}));

    // stop the worker
    // window.workers.stop({name: "process-guitars"});

    // destroy the worker
    // window.workers.destroy({name: "process-guitars"});
})();
[/sourcecode]

Did you check the demo the class? Did you enjoy the blogpost? If you did, follow me @wemakesitesnet, check my personal website or acid.js web.ui for more cool stuff.

Related Posts

Categories and Tags
Links

© 2006 - 2025 Martin Ivanov