Introduction to HTML5 Web Worker, html5worker

Source: Internet
Author: User

Introduction to HTML5 Web Worker, html5worker

Web Worker is a javascript multithreading solution provided by HTML5. We can submit some code with a large amount of computing workload to web Worker to run without freezing the user interface.

I. How to Use Worker

The basic principle of Web Worker is to use the Worker class to load a javascript file in the current javascript main thread to open up a new thread and implement non-blocking execution, it also provides interfaces for data exchange between the main thread and the new thread: postMessage and onmessage.

So how to use it? Let's look at an example:

// Worker. jsonmessage = function (evt) {var d = evt. data; // use evt. data obtains the sent data postMessage (d); // sends the obtained data to the main thread}

HTML page: test.html

<! Doctype html> 

After test.html is opened with chrome, the "hello world" output on the console indicates that the program is successfully executed.

Through this example, we can see that the use of web worker is mainly divided into the following parts:

Main WEB thread:

1. Load a JS file through worker = new Worker (url) to create a worker and return a worker instance.

2. The worker. postMessage (data) method is used to send data to the worker.

3. Bind worker. onmessage to receive data sent by worker.

4. worker. terminate () can be used to terminate the execution of a worker.

New worker thread:

1. send data to the main thread through the postMessage (data) method.

2. Bind The onmessage method to receive data sent by the main thread.

Ii. What can a Worker do?

Knowing how to use web worker can help us solve the problems. Let's look at an example of a fibonacci series.

We all know that in mathematics, the fibonacci series are defined by recursive Methods: F0 = 0, F1 = 1, Fn = F (n-1) + F (n-2) (n> = 2, n, N *), while javascript is commonly implemented:

var fibonacci =function(n) {    return n <2? n : arguments.callee(n -1) + arguments.callee(n -2);};//fibonacci(36)

In chrome, this method is used to execute the 39 fibonacci series in 19097 milliseconds. When the computation is 40, the browser prompts that the script is busy.

Because javascript is executed in a single thread, the browser cannot execute other javascript scripts during the process of listing, and the UI rendering thread will also be suspended, causing the browser to become frozen. Using web worker to put the calculation process of a series into a new thread will avoid this situation. For example:

//fibonacci.jsvar fibonacci =function(n) {    return n <2? n : arguments.callee(n -1) + arguments.callee(n -2);};onmessage =function(event) {    var n = parseInt(event.data, 10);    postMessage(fibonacci(n));};

HTML page: maid

<! Doctype html> 

Open fibonacci.html in chromeand the console will get the following output:

Start calculation: 40 time: 1316508212705
When I calculated the series, the execution time was: 1316508212734.
The time when the timer function is executed in the calculation of the Series: 1316508213735
Result: 102334155 time: 1316508262820 time: 50115

This example shows that the computation of the fibonacci series executed in the worker does not affect the code execution of the main thread and is completely calculated in its own independent thread, the result is sent back to the main thread after the computation is complete.

With web worker, we can execute some complicated operations on the front end without affecting the display of pages, and there is no prompt that the disgusting script is busy.

The following example uses a web worker to calculate the pixels in a scenario. When a scenario is opened, it is drawn in one piece. A worker calculates only one pixel value.

Iii. Other Worker attempts

We already know that a Worker creates a worker by receiving a URL. Can we use a web worker to make jsonp-like requests, we all know that jsonp loads json data by inserting a script tag, while script elements are blocking during loading and execution, it would be nice to use web worker for asynchronous loading.

The following example loads a 169.42KB JSON data in three different ways: web worker, jsonp, and ajax.

/// Aj/webWorker/core. jsfunction $ E (id) {return document. getElementById (id);} onload = function () {// load $ E ('workerload') through web worker '). onclick = function () {var url =' http://js.wcdn.cn/aj/mblog/face 2'; var d = (new Date ()). valueOf (); var worker = new Worker (url); worker. onmessage = function (obj) {console. log ('web worker: '+ (new Date ()). valueOf ()-d) ;};}; // load $ E ('jsonpload') through jsonp '). onclick = function () {var url =' http://js.wcdn.cn/aj/mblog/face 1'; var d = (new Date ()). valueOf (); STK. core. io. scriptLoader ({method: 'post', url: url, onComplete: function () {console. log ('jsonp: '+ (new Date ()). valueOf ()-d) ;}}; // load $ E ('ajaxload') through ajax '). onclick = function () {var url =' http://js.wcdn.cn/aj/mblog/face '; Var d = (new Date ()). valueOf (); STK. core. io. ajax ({url: url, onComplete: function (json) {console. log ('ajax: '+ (new Date ()). valueOf ()-d ));}});};};

HTML page:/aj/webWorker/worker.html

<! Doctype html> 

Set HOST

127.0.0.1 js.wcdn.cn

Access the page through the http://js.wcdn.cn/aj/webWorker/worker.html and load the data in three ways to get the console output:

web worker: 174jsonp: 25ajax: 38

I tried several times and found that the loading time through jsonp and ajax is not much different, but the loading time of web worker is always at a high level. Therefore, it is still slow to load data using web worker, there is no advantage even in the case of a large amount of data. It may be that it is time-consuming for the Worker to initialize a new thread. It has no advantages except for being non-congested during the loading process.

So can web worker support cross-origin js loading? This time we access the page through http: // 127.0.0.1/aj/webWorker/worker.html, when the "web worker loading" button is clicked, there is no reflection in Chrome, and an error is prompted in FF6. From this we can know that web worker does not support cross-origin loading of JS, which is bad news for websites that deploy static files to separate static servers.

Therefore, web worker can only be used to load json data in the same domain. In this respect, ajax can be achieved and the efficiency is higher and more general. Let Worker do what it is good.

Iv. Summary

Web worker looks beautiful, but it is everywhere the devil.

What can we do:

1. Load a JS file to perform a large amount of complex computing without suspending the main process, and communicate with each other through postMessage and onmessage.

2. You can load another script file through importScripts (url) in worker.

3. You can use setTimeout (), clearTimeout (), setInterval (), and clearInterval ()

4. You can use XMLHttpRequest to send requests.

5. Access some attributes of navigator

Limitations:

1. JS cannot be loaded across regions

2. The code in the worker cannot access the DOM.

3. the implementations of Worker in different browsers are not consistent. For example, in FF, worker can be used to create a new worker, but not in Chrome.

4. Not every browser supports this new feature.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.