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

How to use HTML5's WebWorker

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to use the WebWorker of HTML5. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Web Workers is a javascript multithreading solution provided by HTML5. We can let web Worker run some code with a large amount of computation without freezing the user interface.

One: how to use Worker

The basic principle of Web Worker is that in the current main thread of javascript, use the Worker class to load a javascript file to open up a new thread, which has the effect of not blocking execution each other, and provides an interface for data exchange between the main thread and the new thread: postMessage,onmessage.

So how to use it, let's look at an example:

JavaScript Code copies content to the clipboard

/ / worker.js

Onmessage = function (evt) {

Var d = evt.data;// gets the data sent through evt.data

PostMessage (d); / / send the acquired data to the main thread

}

HTML page: test.html

XML/HTML Code copies content to the clipboard

/ / main thread of WEB page

Var worker = new Worker ("worker.js"); / / create a Worker object and pass it the URL of the script to be executed in the new thread

Worker.postMessage ("hello world"); / / send data to worker

Worker.onmessage = function (evt) {/ / receive the data function from worker

Console.log (evt.data); / / output the data sent by worker

}

After opening test.html with a Chrome browser, the console output "hello world" indicates that the program was executed successfully.

From this example, we can see that using web worker is mainly divided into the following parts

WEB main thread:

1. Create a worker by loading a JS file with worker = new Worker (url) and return an instance of worker.

two。 Send data to worker through the worker.postMessage (data) method.

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

4. You can use worker.terminate () to terminate the execution of a worker.

New thread for worker:

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

two。 Bind the onmessage method to receive the data sent by the main thread.

Second: what can Worker do?

Know how to use web worker, so what is the use of it, can help us solve those problems. Let's look at an example of the fibonacci sequence.

As we all know, in mathematics, the fibonacci sequence is defined recursively as follows: F0 ∈ 0 fibonacci (n Mel 1) + F (n mi 2) (n > = 2 m m n N *). The common implementation of javascript is:

JavaScript Code copies content to the clipboard

Var fibonacci = function (n) {

Return n

Onload = function () {

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

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

Var timer2 = (new Date ()) .valueOf ()

Console.log ('result:' + event.data, 'time:' + timer2, 'usage:' + (timer2-timer))

}, false)

Var timer = (new Date ()) .valueOf ()

Console.log ('start calculation: 40 minutes,' time:'+ timer)

SetTimeout (function () {

Console.log ('timer function executed when calculating the sequence', 'time:' + (new Date ()) .valueOf ())

}, 1000)

Worker.postMessage (40)

Console.log ('I executed when calculating the sequence', 'time:' + (new Date ()) .valueOf ())

}

Open fibonacci.html in Chrome and the console gets the following output:

Start calculation: 40 time: 1316508212705

I executed the time when calculating the sequence: 1316508212734

Timer

XML/HTML Code copies content to the clipboard

Function

Time executed when calculating the sequence: 1316508213735

Results: 102334155 time: 1316508262820 time: 50115

This example shows that the calculation of the fibonacci series performed in worker does not affect the code execution of the main thread, it is calculated entirely in its own independent thread, but the result is sent back to the main thread after the calculation is completed.

With web worker, we can perform a large number of complex operations at the front end without affecting the presentation of the page, and without popping up disgusting script busy prompts.

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

Http://nerget.com/rayjs-mt/rayjs.html

Third: other attempts of Worker

We already know that Worker creates a worker by receiving a URL, so can we use web worker to do some jsonp-like requests? you know that jsonp loads json data by inserting script tags, while script elements are blocked during loading and execution, so it would be nice to use web worker to load asynchronously.

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

JavaScript Code copies content to the clipboard

/ aj/webWorker/core.js

Function $E (id) {

Return document.getElementById (id)

}

Onload = function () {

/ / load via web worker

E ('workerLoad'). Onclick = function () {

Var url = 'http://js.wcdn.cn/aj/mblog/face2';

Var d = (new Date ()) .valueOf ()

Var worker = new Worker (url)

Worker.onmessage = function (obj) {

Console.log ('web worker:' + ((new Date ()) .valueOf ()

}

}

/ / load via jsonp

E ('jsonpLoad'). Onclick = function () {

Var url = 'http://js.wcdn.cn/aj/mblog/face1';

Var d = (new Date ()) .valueOf ()

STK.core.io.scriptLoader ({

Method:'post'

Url: url

OnComplete: function () {

Console.log ('jsonp:' + ((new Date ()) .valueOf ()

}

});

}

/ / load via ajax

E ('ajaxLoad'). 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 ()

}

});

}

}

HTML page: / aj/webWorker/worker.html

XML/HTML Code copies content to the clipboard

Worker example: load data

Set up HOST

The code is as follows:

127.0.0.1 js.wcdn.cn

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

The code is as follows:

Web worker: 174

Jsonp: 25

Ajax: 38

After several attempts, it is found that there is little difference in the time to load data through jsonp and ajax, but the loading time of web worker has always been high, so it is relatively slow to load data with web worker, even in the case of a large amount of data. It may be time-consuming for Worker to initialize new threads. There is no advantage except that it is non-blocking during loading.

So whether web worker can support cross-domain js loading? this time we visit the page through http://127.0.0.1/aj/webWorker/worker.html. When we click the "web worker load" button, there is no response under Chrome and an error is prompted under FF6. From this we can see that web worker does not support cross-domain loading of JS, which is bad news for websites that deploy static files to separate static servers.

So web worker can only be used to load json data in the same domain, and ajax can already do this, and it is more efficient and general-purpose. Let Worker do what he is good at.

Four: summary

Web worker looks beautiful, but it's full of demons.

What can we do:

1. You can load a JS to do a lot of complex calculations without suspending the main process, and communicate through postMessage,onmessage

two。 You can load additional script files in worker through importScripts (url)

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

4. You can use XMLHttpRequest to send requests

5. You can access some of the properties of navigator

What are the limitations:

1. Cannot load JS across domains

Code in 2.worker cannot access DOM

3. Different browsers have different implementations of Worker. For example, new worker is allowed to be created in worker in FF, but not in Chrome.

4. Not every browser supports this new feature

On how to use HTML5 WebWorker to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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