Over a million developers have joined DZone.

Importing Scripts in Web Workers

· Web Dev Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

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) {

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.


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.

The Web Dev Zone is brought to you by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".


Published at DZone with permission of Gil Fink , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}