HTML5 Web Worker

Source: Internet
Author: User
Tags date interface return thread client access

The concept of a worker thread (WEB workers) is proposed in HTML5, which is a multithreaded concept that allows a large number of calculated code to be run by web workers without freezing the user interface.

The three major features of WEB workers:

1) able to run for a long time (response)

2 Ideal Start-up performance

3 Ideal memory consumption

WEB workers allows developers to write background programs that can run for a long time without being interrupted by the user, to execute transactions or logic, and to ensure that the page responds to the user in a timely manner.

Web workers provides a way for scripts on a Web front-end Web page to run in a background process. Once it is created, the WEB workers can send a task request to the task pool via PostMessage, and then return the message via PostMessage to the creator-specified event handler (captured by OnMessage). The Web workers process can handle tasks without affecting the user interface, and it can also use XMLHttpRequest to handle I/O, but typically, background processes, including WEB workers processes, cannot manipulate the DOM. If you want the background program to process results that change the DOM, you can only handle it by returning the message to the creator's callback function.



A new Worker instance needs to be created in the JavaScript code of the client page, which is the name of the JavaScript file that needs to run on another thread. The OnMessage event is then monitored on this instance. The last JavaScript in the other thread can pass data between the two threads by calling the PostMessage method.



In the main program, create a worker instance and listen for OnMessage events

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>test Web worker</title>
<script type= "Text/javascript" >
function init () {
var worker = new Worker (' compute.js ');
The event argument has the Data property, which is the result that is returned in the child thread
worker.onmessage= function (event) {
The result returned by the handle thread is added to the DIV
document.getElementById ("Result"). InnerHTML + =
event.data+ "<br/>";
};
}
</script>
<body onload= "init ()" >
<div id= "Result" ></div>
</body>


The compute.js in the client opens up a new thread that does not block execution and provides a data interface between the main thread and the new threads. Just a simple repeated addition and operation, and finally through the PostMessage method to return the results to the main thread, the purpose is to wait for some time. In this time, the main thread should not be blocked, users can drag and drop the browser, to reduce the size of the browser window and other operations to test this phenomenon. The result of this non-blocking main thread is what the WEB workers want to achieve.


Call the PostMessage method in Compute.js to return the result of the calculation


var i=0;

function Timedcount () {
for (Var j=0,sum=0;j<100;j++) {
for (Var i=0;i<1000000;i++) {
Sum+=i;
}
}
Call PostMessage to send a message to the main thread
PostMessage (sum);
}

PostMessage ("Get the time before the calculation," +new date ());
Timedcount ();
PostMessage ("Get the time after the calculation," +new date ());

Demo Address: http://lovermap.sinaapp.com/test/test.html

Because JavaScript is single-threaded, the browser cannot execute other JavaScript scripts during complex operations, and the UI render thread is suspended, causing the browser to enter zombie state. Using web worker to put the calculation of a sequence into a new thread will prevent this from happening.

In addition to using Web worker to load a JS for a large number of complex computations without suspending the main process and communicating through Postmessage,onmessage, additional script files can be loaded through the importscripts (URL) in the worker, using the SetTimeout (), cleartimeout (), SetInterval (), and clearinterval (), use XMLHttpRequest to send requests to access some properties of the navigator.

But there are some limitations :

1. Cannot load JS across domains (homology policy limit)

2.worker code cannot access Dom

3. Different browsers are not consistent with the implementation of the worker

4. Not every browser supports this new feature



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.