Importing Scripts in Web Workers

February 17, 2013

no comments

Importing Scripts in Web Workers

Importing Scripts in Web WorkersWhile implementing a background task in a HTML5/JavaScript Windows Store app, I had the need to import scripts in the background task. Since background tasks are implemented on top of Web Workers, I used the importScripts function which is a global function that Web Workers can use to import scripts. In this post I’ll explain how to use the function and show a simple use example.

The importScripts Function

The importScripts function is a global function that Web Workers can use to load and execute additional scripts. You will use that function when you want to load utilities or libraries like Underscore.js and story.js. The function receives zero or more URI strings to import. The following example shows how to use the function:

importScripts(); // imports nothing
importScripts('story.js'); // imports story.js
importScripts('//Microsoft.WinJS.1.0/js/base.js', 'story.js'); // imports WinJS and story.js

The scripts are loaded synchronously and the function doesn’t returns up until all the scripts have been loaded and executed. Once the scripts are loaded and the function returns, you will be able to use the scripts functionality within the Web Worker. If an error occurs during a script importing process, a NETWORK_ERROR is thrown by the importScripts function and the scripts that follow won’t be executed.

Lets look at an example:

(function () {
    "use strict";
 
    self.importScripts("/js/algorithm.js", "/js/helpers.js");
 
    function run() {
        if (!Helpers.networkAvailable()) {
            self.postMessage("The network is not available.");
        }
        else {
            Algorithem.run().then(function (result) {
                self.postMessage(result);
            });
        }
    }
 
    run();
}());

In the previous script, which is executed in a Web Worker, I first import an algorithm and a helpers scripts. The algorithm needs network in order to execute so in the run function I first check if network available and if yes I run the algorithm.

Summary

In conclusion, the importScripts function can help you to load and execute utilities and libraries into Web Workers runtime. That will help you to make Web Workers code more modular and maintainable.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>