Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the asynchronous execution of Web Worker and related overview in HTML5

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I will talk to you about the asynchronous execution of Web Worker in HTML5 and the related overview, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

Javascript execution mechanism

Before HTML5, JavaScript runs in a single thread in browsers. Although there are many ways to simulate multithreading (for example, setinterval method in Javascript, setTimeout method, etc.), in essence, the program is still run by the JavaScript engine in a single-thread scheduling way. The worker thread introduced in HTML5 enables the browser-side Javascript engine to execute Javascript code concurrently, thus realizing a good support for browser-side multithread programming.

Multithreading in Javascript-WebWorker

Web Worker in HTML5 can be divided into two different thread types, one is dedicated thread Dedicated Worker, and the other is shared thread Shared Worker. The two types of threads have different uses.

Special web worker

The dedicated worker is connected to the script that created it, and it can communicate with other worker or browser components, but it cannot communicate with DOM. The special meaning, I think, is that this thread handles only one requirement at a time. Dedicated threads are implemented in all major browsers except IE and can be safely used.

Create thread

Creating a worker is as simple as passing the file name of the JavaScript file that needs to be executed in the thread to the constructor.

Thread communication

The postMessage and onmessage methods of the thread object are used to communicate between the main thread and the child thread. No matter who sends data to whom, the sender uses the postMessage method, and the receiver uses the onmessage method to receive the data. PostMessage has only one parameter, and that is the data passed, and onmessage also has only one parameter. If event is assumed, the received data will be obtained through event.data.

Send JSON data

JSON is something natively supported by JS, so you don't have to use it. Just use JSON to transmit complex data. For example:

The code is as follows:

PostMessage ({'cmd':' init', 'timestamp': Date.now ()})

Handling error

When a thread has an error, its onerror event callback is called. So the simple way to handle errors is to hook up the thread instance's onerror event. The callback function has an argument error, which has three fields: message-error message; filename-script file where the error occurred; and lineno-the line on which the error occurred.

Destroy thread

Inside the thread, the thread uses the close method to destroy itself. In the main thread outside the thread, use the terminate method of the thread instance to destroy the thread.

Let's look at the basic operation of a thread from an example:

HTML Code:

The code is as follows:

Web worker fibonacci

Onload = function () {

Var worker = new Worker ('fibonacci.js')

Worker.onmessage = function (event) {

Console.log ("Result:" + event.data)

}

Worker.onerror = function (error) {

Console.log ("Error:" + error.message)

}

Worker.postMessage (40)

}

Script file fibonacci.js code:

The code is as follows:

/ / fibonacci.js

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

}

Put them in the same directory, run the page file, check the console, and you can see the results of the run.

Here's another thing: in the main thread, the onmessage event can be hooked in another way:

The code is as follows:

Worker.addEventListener ('message', function (event) {

Console.log ("Result:" + event.data)

}, false)

Personally, I think it's troublesome, so it's better to use onmessage directly.

Use other script files

Worker threads can use the global method importScripts to load and use other intra-domain script files or class libraries. For example, the following are legal ways to use:

The code is as follows:

ImportScripts (); / * imports nothing * /

ImportScripts ('foo.js'); / * imports just "foo.js" * /

ImportScripts ('foo.js',' bar.js'); / * imports two scripts * /

After import, you can use the methods in these files directly. Take a look at a small online example:

The code is as follows:

/ * *

* use the importScripts method to introduce external resource scripts, where we use the mathematical formula calculation tool library math_utilities.js

* when the JavaScript engine has finished loading the resource file, continue to execute the following code. At the same time, the following code can access and call

* variables and methods defined in the resource file.

* * /

ImportScripts ('math_utilities.js')

Onmessage = function (event)

{

Var first = event.data.first

Var second = event.data.second

Calculate (first,second)

}

Function calculate (first,second) {

/ / do the calculation work

Var common_divisor=divisor (first,second)

Var common_multiple=multiple (first,second)

PostMessage ("Work done!" +

"The least common multiple is" + common_divisor +

"and the greatest common divisor is" + common_multiple)

}

Some netizens on the Internet also thought of using the importScripts method here to solve the problem of preloading resources (browsers preload resources without parsing and executing them). The reason is also very simple.

Thread nesting

You can also create child threads in the worker thread, and all kinds of operations are the same.

Synchronization problem

Worker has no locking mechanism, and the synchronization problem of multithreading can only be solved by code (such as defining signal variables).

Shared SharedWebWorker

Shared web worker is mainly suitable for the problem of concurrent multiple connections. Because you have to deal with multiple connections, its API is slightly different from the dedicated worker. In addition to this, shared web worker, like dedicated worker, does not have access to DOM, and access to form properties is restricted. Shared web worker also cannot span communication.

Page scripts can communicate with shared web worker, however, slightly different from private web worker (which uses an implicit port to communicate), communication is done explicitly by using a port (port) object and attaching a message event handler.

After receiving the first message from the web worker script, the shared web worker attaches an event handler to the active port. Typically, the handler runs its own postMessage () method to return a message to the calling code, and then the port's start () method generates a valid message process.

Look at the only example that can be found online: create a shared thread to receive instructions sent from different connections, then implement your own instruction processing logic, and return the results to different connected users after instruction processing.

HTML Code:

The code is as follows:

Shared worker example: how to use shared worker in HTML5

Var worker = new SharedWorker ('sharedworker.js')

Var log = document.getElementById ('response_from_worker')

Worker.port.addEventListener ('message', function (e) {

/ / log the response data in web page

Log.textContent = e.data

}, false)

Worker.port.start ()

Worker.port.postMessage ('ping from user web page..')

/ / following method will send user input to sharedworker

Function postMessageToSharedWorker (input)

{

/ / define a json object to construct the request

Var instructions= {instruction:input.value}

Worker.port.postMessage (instructions)

}

Shared worker example: how to use shared worker in HTML5

Send instructions to shared worker:

Script file code:

The code is as follows:

/ / create a shared thread to receive instructions sent from different connections, and return the results to different connected users after instruction processing.

Var connect_number = 0

Onconnect = function (e) {

Connect_number = connect_number+ 1

/ / get the first port here

Var port = e.ports [0]

Port.postMessage ('A new connection! The current connection number is'

+ connect_number)

Port.onmessage = function (e) {

/ / get instructions from requester

Var instruction=e.data.instruction

Var results=execute_instruction (instruction)

Port.postMessage ('Request:' + instruction+' Response'+ results

+ 'from shared worker...')

}

}

/ *

* this function will be used to execute the instructions send from requester

* @ param instruction

* @ return

, /

Function execute_instruction (instruction)

{

Var result_value

/ / implement your logic here

/ / execute the instruction...

Return result_value

}

In the shared thread example above, a shared thread object is constructed on the main page, that is, each user connection page, and then a method postMessageToSharedWorker is defined to send instructions to the user from the shared thread. At the same time, connect_number is defined in the implementation snippet of the shared thread to record the total number of connections to the shared thread. After that, the onconnect event handler is used to accept connections from different users and parse the instructions they pass. Finally, a method execute_instruction is defined to execute the user's instructions, and the result is returned to each user after the instruction execution is completed.

Instead of using the worker thread's onmessage event handler as in the previous example, we use a different way, addEventListener. In fact, as mentioned earlier, the principles of the two implementations are basically the same, except that there is a slight difference here. If you use addEventListener to accept messages from shared threads, you should first use the worker.port.start () method to start the port. You can then receive and send messages as normally as the worker thread does.

Final statement

What can be done in a thread:

1. You can use functions such as setTimeout (), clearTimeout (), setInterval (), clearInterval (), etc.

two。 You can use navigator objects.

3. You can use XMLHttpRequest to send requests.

4. You can use Web Storage in threads.

5. You can use self in a thread to get the scope of this thread.

What cannot be done in a thread:

1. DOM/BOM objects other than navigator, such as window,document, cannot be used in a thread (if you want to operate, you can only send a message to the worker creator and operate through a callback function).

two。 Variables and functions in the main thread cannot be used in a thread.

3. Operation commands that have a "suspend" effect, such as alert, cannot be used in threads.

4. JS cannot be loaded across domains in a thread.

Threads also consume resources, and using threads can bring some complexity, so don't use additional threads if there is no good reason to use them.

After reading the above, do you have any further understanding of Web Worker asynchronous execution and related overview in HTML5? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report