WebWorkers

HTML5, CSS3 and JavaScript Experiments and Insight Website

Try Semtex – the new HTML5, CSS3 and JavaScript UI framework!

I am pleased to announce that I’ve just finished my latest endeavour – HTML5, CSS3 and JavaScript Experiments and Insight, and most of the code samples and demos from my blog have been moved there in and new and convenient code-listing and demo form. From now on, each new blog post will be accompanied by a dedicated page on that website on which my readers will be able to have a look at the code, run the example and eventually download it.

Enjoy HTML5, CSS3 and JavaScript Experiments and Insight and have a great rest of the week!

Advertisements

JavaScript Wrapper for the HTML5 WebWorkers API

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

(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;
})();

Using the Class

(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"});
})();

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

Useful JavaScript Classes and Functions

  • Crossbrowser image reflections enabler JavaScript class.
  • JavaScript Mapper Class for RESTFul Methods – Recently I had to work with a bunch of RESTFul API methods, so instead of defining manually separate calls/methods for each API request, I decided to do it viceversa – to force JavaScript to create these methods automatically for me out of the RESTFul API by providing the URLS and other required data.
  • XML to JSON JavaScript Objectifier Class – Simple XML to JSON objectifier. It can be used with custom or public XML, REST APIs such as Last.FM, RSS and ATOM feeds, sitemaps, etc by converting the XML server responses to native JSON objects in the browser which are then instantly accessible by its simple to use JavaScript methods.
  • URI to JSON Serializer Class – Tiny JavaScript class, using the HTMLAnchorElement interface to convert URI string into a JSON object.  The object returned by the function contains hash, host, hostname, parameters key-value map, pathname, port and protocol. Works with all major browsers (Firefox, Chrome, Safari, Opera, IE6-10).
  • IMDB Fetcher – Experimental IMDB JavaScript and PHP API – Makes possible the execution of cross-domain AJAX queries to IMDB and returns a JSON data object for the requested movie. What is currently supported – movie title, poster, release date, description, actor(s), director(s), IMDB and MPAA rating, running time, etc.
  • Quick and Dirty Localization With JavaScript – A quick and dirty JavaScript localization routine that provides basic localization (no support for plurals, etc), operates on the DOM of the page and uses data-lang attribute for language keys storage. Lokalizr works with all major browsers, beginning with IE8.
  • JavaScript Instance Name Finder – Small JavaScript function that checks for instances of an object within a defined scope and returns an array of instances’ variable names that can be used for different purposes.
  • HTML5 Placeholder Enabler – The solution presented in this post checks for the availability of the placeholder attribute in textboxes, and if it is not available applies its content as value to the elements that contain it.
  • HTML 5 Details Element Enabler – According to WhatWG, the “<details /> element represents a disclosure widget from which the user can obtain additional information or controls“. In brief, you can use it to create panelbar elements without JavaScript, as the expand / collapse functionality is native to it. Currently (October, 2011), the only browser which supports <details /> is Google Chrome, so if you are eager to start using this element on your pages, you can do so with the help of a few lines of JavaScript to make sure it works on all browsers.
  • WebWorkers JavaScript class.
  • Classless JavaScript inheritance.
  • JavaScript class augmenter.
  • JavaScript API for TinyURL.
  • HTML Validation Bookmarklet.
  • JavaScript Template Engine.