Use Web workers to improve web application availability

Source: Internet
Author: User
This article from: http://www.ibm.com/developerworks/cn/web/wa-webworkers? CMP = dwskl & cv= DW & Ct = dwcon & Cr = cn_ccid & CCY = Cn

Author:
Wei (Marshall) Shi, software developer, ibmbo Wang, software engineer, IBM

Introduction:Web workers, a new JavaScript programming model, can improve the interaction of your web applications. With it, you can run javascript in a multi-threaded way, and you can run scripts in the background without relying on any User Interface scripts. This article introduces Web workers and guides you through a practical example to show you how to apply web workers to your web applications.

Introduction

With the emergence of Ajax and Web 2.0 applications, end users are spoiled by Web applications that respond quickly. To make Web applications respond faster, the bottleneck must be solved. Bottlenecks include the huge amount of JavaScript and background I/O calculations, which need to be removed from the main UI display process and handed over to Web workers for processing.

Web workers specifications provide the ability to run scripts in the background without relying on any User Interface scripts. Scripts that run for a long time are not interrupted by scripts that respond to clicks or other user interactions. Web workers allows long-term tasks and does not affect page responses.

Before the emergence of Web workers, JavaScript was the core of modern web applications. JavaScript and Dom are essentially single-threaded: Only one JavaScript method can be executed at any time. Even if your computer has four kernels, only one kernel is busy during long-term computing. For example, when you calculate the optimal orbit to reach the moon, your browser cannot render an animation showing the trajectory, and-at the same time-respond to user events (such as mouse clicks or keyboard input ).

In the original HTML 5, the Web workers API is separated and becomes an independent specification. Some browsers, such as Firefox 3.5, chrome 3, and Safari 4, can implement most web workers APIs. Click here to view how your browser can better support web workers.

Web workers breaks the traditional JavaScript single-thread mode and introduces the multi-thread programming mode. OneWorkerIs an independent thread. Web applications that have multiple tasks to process do not need to process tasks one by one. Conversely, applications can assign tasks to different workers.

In this article, you will learn about the web workers API. An instance guides you to gradually use web workers to build a web page.

From the following
Download the source code of the example in this article.

Back to Top

Basic Concepts

Basic Components of Web workers:

Worker
A new thread runs in the background and does not block any main User Interface scripts (called as background scripts ). Workers is relatively heavyweight and should not be used on a large scale.

A worker can execute many tasks, including parallel computing, background I/O, and client database operations. Worker should not interrupt the main ui or operate the DOM directly; it should return a message to the main thread and let the main thread update the main UI.

Subworker
The worker created in a worker. Subworkers must be the same root as the parent page. The URI of subworkers is determined based on the address of the parent worker rather than the address of its own page.
Shared worker
A worker that can be used by multiple pages through multiple connections. The working method of shared worker is slightly different from that of common worker. Only a small number of browsers support this feature.

Back to Top

Web workers API

This section describes the basic concepts of Web workers APIs.

Create a worker

To create a new worker, you only need to call the worker constructor. The worker Script URL is the only parameter. Start a new thread (or a new process, depending on your browser's implementation) when the worker is created ).

When worker completes the work or encounters an error, you can useonmessageAndonerrorProperties get notifications from worker. Listing 1 is an example worker.

List 1. Example worker myworker. js

 // receive a message from the main JavaScript threadonmessage = function(event) {// do something in this workervar info = event.data;postMessage(info + “ from worker!”);};            

If you run the JavaScript code in Listing 2, you will get "Hello world from worker ".

List 2. worker in the main JavaScript thread

// create a new workervar myWorker = new Worker("myWorker.js");// send a message to start the workervar info = “Hello World”;myWorker.postMessage(info);// receive a message from the workermyWorker.onmessage = function (event) {// do something when receiving a message from workeralert(event.data);};

Terminate worker

A worker is a thread and an OS-level object with high resource consumption. Call
terminate
Method to terminate a running worker. A worker thread or process can be terminated without the opportunity to complete its operations and clean itself. Listing 3 is an example.

Listing 3. Terminating myworker

myWorker.terminate();            

Error Handling

Similar to common JavaScript code, runtime errors can also be found in the running worker. To handle these errors, you must createonerrorIf an error occurs during the script running, the handler is called. To prevent default activity, the worker can call the worker error event
preventDefault()Method.

Listing 4. Add an error handle to myworker

myWorker.onerror = function(event){console.log(event.message);console.log(event.filename);console.log(event.lineno);}

The error event has the following three fields, which may be helpful for debugging:

  • message: A readable error message
  • filename: Name of the script file with the error message
  • lineno: Number of rows of script files with error messages

Import scripts and libraries

The worker thread can access a global function,importScripts()This function supports importing scripts and databases to their scopes. It can neither receive parameters nor receive URLs of multiple resources to be imported as parameters.

Listing 5. Import script

//import nothingimportScripts();//import just graph.jsimportScripts('graph.js');//import two scriptsimportScripts('graph.js', 'controller.js');

Back to Top

Use Web workers

This section briefly introduces a practical use case for Web workers. This example shows a page containing multiple Dojo-based website displayer widgets. These widgets used to use IFRAME to display a website. When there is no web workers, you must obtain the widget definitions through Ajax requests and display them in an independent JavaScript thread. If the widget definition contains a large amount of data, this process is very slow.

This example creates some workers to obtain the widget definition. Each worker task gets a widget definition and notifies the main UI JavaScript thread to display it. This is a fast solution.

This example uses dojo 1.4. If you want to run this example in your browser, download the dojo library used in this article (see
References) and source code (see
Download ). Figure 1 shows the structure of the sample application.

Figure 1. Web workers Application

In Figure 1:

  • Lib is a dojo library.
  • /Widgets/websitedisplayer. JS is a dojo-based website displayer implementation.
  • /Loadwidget/widgets/widgetdefinition [0... 3] is the definition of each website displayer widget.
  • /Loadwidget/workers. JS is the worker implementation.
  • /Loadwidget/XMLHttpRequest. JS is a JS library containing a creationXMLHttpRequst.
  • /Loadwidget/loadwidget.html is the main page of the demo with activated web workers. It will be the main JavaScript thread.
  • /Loadwidget/LoadWidget-none-web-workers.html is the home page that is implemented without web workers.

Create a website displayer widget

The website displayer widget is a very simple Dojo-titlepane-dijit-based widget. It displays the UI of A canonicalized title bar, as shown in figure 2.

Figure 2. Website displayer widget

Listing 6 is the websitedisplayer. js code.

Listing 6. websitedisplayer. js content

dojo.require("dijit._Widget");dojo.require("dijit._Templated");dojo.require("dijit.TitlePane");dojo.declare("loadWidget.WebsiteDisplayer", [dijit.TitlePane], {    title: "",    url: "",    postCreate: function() {var ifrm = dojo.create("iframe", {           src: this.url,    style: "width:100%;height:20%;"});dojo.place(ifrm, this.domNode.children[1], "first");this.inherited(arguments);var contentFrame = this.domNode.children[1].children[0];if (contentFrame.attachEvent) {    contentFrame.attachEvent("onload",function() {    dojo.publish("frameEvent/loaded");}    );} else {    contentFrame.onload = function() {dojo.publish("frameEvent/loaded");    };}    }});

Create a worker

To implement worker. JS, import a global Javascript file XMLHttpRequest. JS, which contains the Global MethodcreatXMLHTTPRequest. This method returns
XMLHttpRequestObject.

WorkerXMLHttpRequestSend to the server, and then retrieve the widget definition and return it to the main thread. Listing 7 and 8 show an example.

Listing 7. Worker. js content

importScripts("XMLHttpRequest.js");onmessage = function(event) {  var xhr = creatXMLHTTPRequest();  xhr.open('GET', 'widgets/widgetDefinition' + event.data + '.xml', true);  xhr.send(null);  xhr.onreadystatechange = function() {    if (xhr.readyState == 4) {      if (xhr.status == 200 || xhr.status ==0) { postMessage(xhr.responseText);      } else { throw xhr.status + xhr.responseText;      }    }   }}

Listing 8. widgetdefinition0.xml

<div dojoType="loadWidget.WebsiteDisplayer" title="This is Test Widget 0"   url="http://www.yahoo.com" ></div>

Create a master web page

The main web page is where you perform these operations: create several workers, send messages to workers, start workers, retrieve messages from workers, and use the retrieved messages to operate the main UI.

Listing 9. main web page

Embed the homepage into a web application and run it. Result 3 is displayed.

Figure 3. Use Web workers to load Widgets

To see the difference between using web workers and not using web workers, run loadwidget.html and the LoadWidget-none-web-workers.html respectively, and then view the results. Note that the page without running Web workers is faster than the page with running Web workers, because the sample code processes too little data. In fact, the time saved balances the cost of starting worker.

Back to Top

Tips for using web workers

The above example only involvesXMLHttpRequestAnd computing. If you want worker to process more complex tasks, such as processing a large amount of computing, it will be a powerful feature. Learn some tips before applying this cool technology to your project.

Dom cannot be accessed in workers

For security purposes, workers cannot directly operate on HTML. Multi-threaded operations on the same Dom may cause thread security problems. The advantage is that you no longer worry about multithreading security issues in worker implementation.

This has some limitations when developing worker. You cannot call it in worker.alert()This is a very popular method for debugging JavaScript code. You cannot call
document.getElementById()Because it can only retrieve and return variables (may be strings, arrays, JSON objects, and so on ).

Available objects in worker

Although worker cannot accesswindowObject, but can be accessed directlynavigator. You can also
navigator
Object AccessappName,appVersion,platformAnd
userAgent.

locationObjects can be accessed in read-only mode. You canlocationObjecthostnameAnd
port.

Also supported by workerXMLHttpRequest, As shown in this example. With this feature, you can add a large number of extensions of interest to the worker.

In addition:

  • importScripts()Method (access the script file in the same domain)
  • Javascript objects, suchObject,Array,Date,MathAnd
    String
  • setTimeout()AndsetInterval()Method

postMessageData Type carried in

postMessageBecause it is the main method of the main JavaScript thread, used to interact with workers. However, now
postMessageThe data types carried in are limited to the local JavaScript type, such as array, date, math, string, and JSON. Custom JavaScript objects with complex structures cannot be well supported.

Sample source code download: http://www.ibm.com/developerworks/apps/download/index.jsp? Contentid%769%&filename%source.zip & method = http & locale = zh_cn

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.