HTML5WebApppart4: Use WebWorkers to accelerate your mobile Web application (on )...-

Source: Internet
Author: User
Tags basic html page
Web applications have been confined to a single-threaded world for a long time. This does limit the actions of developers in their code, because there is a risk of freezing the application UI for anything that is too complex. By introducing multithreading into Web applications, WebWorkers reversed this disadvantage ...,.

Web applications have been confined to a single-threaded world for a long time. This does limit the actions of developers in their code, because there is a risk of freezing the application UI for anything that is too complex. By introducing multithreading into Web applications, Web Workers has reversed this disadvantage. This is especially useful for mobile Web applications where most application logic is on the client. In this article, you will learn how to use Web Workers and find out which tasks are most suitable for them. You will also see how other HTML 5 technologies can improve the efficiency of those technologies.


In this article, you will use the latest Web technology to develop Web applications. Most of the code here is only the core technology of HTML, JavaScript, and CSS-all Web developers. The most important tool is the browser used for testing. Most of the Code in this article will be run on the latest desktop browser, but there are some exceptions that we will explain in this article. Of course, you must also test on a mobile browser. Therefore, you need the latest iPhone and Android SDKs. This article uses iPhone SDK 3.1.3 and Android SDK 2.1. The example in this article also uses a proxy server to access remote services from a browser. This proxy server is a simple Java servlet, but it can also be easily replaced by a proxy written in PHP, Ruby, and other languages. Obtain the link.

Multithreading JavaScript on mobile devices

For most developers, multithreading or concurrent programming is not new. However, JavaScript is not a language that supports concurrent programming. The JavaScript creator believes that concurrent programming is prone to problems and is unnecessary for a language like JavaScript designed to execute simple tasks on Web pages. However, as Web pages have evolved into Web applications, the complexity of tasks completed using JavaScript has increased significantly, and JavaScript has been given the same requirements as other languages. At the same time, developers who work in other languages that support concurrent programming often face ultra-high complexity that comes with concurrent primitives such as threads and mutexes. In fact, several new languages such as Scala, Clojure, and F # have developed recently, and they may all simplify concurrency.

The Web Worker specification is not only used to add concurrency to JavaScript and Web browsers, but also in a smart way. This method will increase the capabilities of developers, however, they will not be provided with a tool that will cause problems. For example, for many years, desktop application developers have been using multithreading to allow their applications to access multiple I/O resources to avoid freezing the UI while waiting for these resources. However, when these threads Change shared resources (including the UI), such applications usually encounter problems because such behavior may cause application freezing or crashes. With Web Workers, this will not happen. Derivative threads cannot access resources accessed by the main UI thread. In fact, the code in the derivative thread cannot even be in the same file as the Code executed by the main UI thread.

You must even provide an external file as part of the constructor, as shown in Listing 1.

This process uses three resources:

  1. Web page JavaScript executed on the main thread (I call itPage script).
  2. WorkerObject, which is a JavaScript Object used to execute the Web Worker function.
  3. The script to be executed on the new derived thread. I call itWorker script.

Let's first look at the page script in Listing 1.

List 1. Use a Web Worker in the page script

var worker = new Worker("worker.js?6.1.3");worker.onmessage = function(message){    // do stuff};worker.postMessage(someDataToDoStuffWith);

In listing 1, you can see the three basic steps for using Web Workers. First, you create a Worker object and pass it the URL of the script that will be executed in the new thread. All code executed by the Worker must be included in a Worker script, and the URL of the script will be passed to the Worker constructor. The URL of this Worker script is restricted by the browser's same-origin policy-it must be from the same domain that loads the page. The page has been loaded with the page script that is creating the Web Worker.

The next step is to useonmessageFunction specifies a callback processor function. This callback function will be called after the Worker script is executed.messageIs the data returned from the Worker script. You can process the message at will. The callback function is executed on the main thread, so it can access the DOM. The Worker script runs in a different thread and cannot access the DOM. Therefore, you need to return the data from this Worker script to the main thread, where, you can safely modify the DOM to update the UI of your application. This is a key feature of the non-shared Design of Web Workers.

The last line in Listing 1 shows how to call the WorkerpostMessageFunction to start it. Here, you pass a message (again, it is only data) to the Worker. Of course,postMessageIs an asynchronous function; when you call it, it returns immediately.

Now, check the Worker script. The code in Listing 2 comes from listing 1.worker.jsFile Content.

List 2. A Worker script

importScripts("utils.js?6.1.3");var workerState = {};onmessage = function(message){     workerState =;      // do stuff with the message    postMessage({responseXml: this.responseText});}

As you can see, this Worker script has its ownonmessageFunction. This function is called from the main threadpostMessage. Data transmitted from the page script is passedmessageObjectpostMessageFunction. You can searchmessageObjectdataTo access the data. When you have processed the data in the Worker scriptpostMessageThe function returns data to the main thread. The main thread can also access this data by accessing the data attribute of the message it receives.

So far, you have seen this simple but powerful semantics of Web Workers. Next, you will learn how to apply this semantics to accelerate mobile Web applications. Before that, it is necessary to discuss device support. After all, these are mobile Web applications, and it is very important for mobile Web application development to process the functional differences between different browsers.

Device Support

Since Android 2.0, the Android browser has full support for HTML 5 Web Worker specifications. At the time of writing this article, the latest Android device (including the very popular Motorola Droid) has been configured with Android 2.1. In addition, this feature is fully supported on Mozilla Fennec and Windows Mobile devices on Nokia devices running the Maemo operating system. The iPhone is the one that deserves attention. IPhone OS 3.1.3 and 3.2 (OS versions running on iPad) do not support Web Workers. However, this feature has been supported on Safari, so it should be a time issue to appear on the Mobile Safari browser running on the iPhone. Given the dominant position of the iPhone (especially in the United States), it is best not to rely on the presence of Web Workers, do not use them to enhance your mobile Web applications only when you detect them. After realizing this, let's take a look at how to use Web Workers to accelerate your mobile Web applications.

Use Workers to improve performance

The Web Worker support on the smartphone browser is very good, and it has been continuously improved. This raises a question: when do I need to use Workers in a mobile Web application? The answer is simple: you need to complete time-consuming tasks anytime. Some examples show how to use Workers for intensive mathematical calculations, such as calculating the circumference rate of 10 thousand digits. It is very likely that you never need to execute such a computing on a Web application, and the chances of executing such a computing on a mobile Web application are smaller. However, retrieving data from remote resources is quite common, which is also the focus of this example.

In this example, you will retrieve a list of Daily Deals (changing transactions every day) from eBay. This transaction list contains brief information about each transaction. For more details, you can use the Shopping API of eBay. When a user browses this transaction list and selects the item of interest, you will use Web Workers to prefetch this additional information. To access all the eBay data from your Web application, you need to use a generic proxy to process the browser's same-origin policy. A simple Java servlet will be used for this proxy, which is included in the Code in this article, but not shown here separately. Instead, we will focus on the code that processes Web Workers. Listing 3 shows the basic HTML page of the transaction application.

Listing 3. Transaction Application HTML

     Worker Deals    

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: 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.