Home  >  Article  >  Web Front-end  >  How to implement Web Worker in H5 multi-threading

How to implement Web Worker in H5 multi-threading

php中世界最好的语言
php中世界最好的语言Original
2017-12-04 10:39:461828browse

Many people have asked me, how to implement Web Worker in H5 multi-threading? When we talk about this question, first of all, you need to know what is a Web Worker, so today we will answer this question for you.

When the JavaScript code is handed over to the Web Worker for execution in the background, the page can still respond to user operations while the JavaScript is running to prevent the page from getting stuck. Users can create multiple Worker threads so that they can do some small-scale distributed computing and other work in the foreground.

Distributed computing is a computing method, which is opposite to centralized computing. With the development of computing base, some applications require very huge computing power to complete. If centralized computing is used, it will take a long time to complete. Distributed computing breaks the application into many small parts and assigns them to multiple computers for processing. This can save overall computing time and greatly improve computing efficiency.

The small-scale distributed computing I mentioned above is an efficient use of CPU multi-cores.

Things that cannot be done in the thread:

Web Worker cannot access DOM node It is normal that DOM cannot be shared, otherwise the DOM is being manipulated here, and the Worker is also operating there. Manipulating the DOM, or even deleting the DOM, isn't this a conflict? Web Worker cannot access global variables or global functions Web Worker cannot call functions such as alert() or confirm. Web Worker cannot access browser global variables such as window and document

Things that can be done in the thread:

Can use setTimeout(), clearTimeout(), setInterval(), clearInterval() and other functions Can use navigator object Can use XMLHttpRequest To send a request, you can use Web Storage and you can use self to obtain the scope of this thread.

Web Worker can be divided into two types: dedicated thread (dedicated web worker) and shared thread (shared web worker). A dedicated thread can only be accessed by the page that created it and ends when the current page is closed; while a shared thread can be accessed by multiple pages and will only end when all associated pages are closed. Compared with dedicated threads, shared threads are slightly more complicated.

Detect browser support for Web Worker

if(typeof(Worker)!=="undefined")  {  
    // Yes! Web worker support!  
}  else  {  
    // Sorry! No Web Worker support..  
}

Create Web Worker objects and files:

The following is probably the simplest entry-level JS multi-threaded Demo:

Write picture description here

Create thread

var worker = new Worker(url);//url is the JavaScript file name and corresponding path that needs to be executed in the thread

Thread communication

To communicate between the main thread and the child thread, the postMessage and onmessage methods of the thread object are used. No matter who sends data to whom, the sender uses the postMessage method, and the receiver uses the onmessage method to receive data. Both postMessage and onmessage have only one parameter. Assuming that the parameter of onmessage is event, the received data is obtained through event.data.

Destroy the thread

Outside the thread, use the terminate method of the thread instance to destroy the thread. Inside the thread, use the close method, and the thread destroys itself

Handling errors

When an error occurs in a thread, its onerror event callback will be called.

var worker = new Worker("test.js");
worker.onerror = function(event){
    console.log("load web worker error." + event);
}

Send JSON data

Use JSON to send complex data!

Use importScripts in Web Worker to load external JS

In the HTML page, use the 3f1c4e4b6b16bbbd69b2ee476dc4f83a

tag to load external JS files, and the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag also Support cross-domain loading of JS.

Be careful in Web Worker!

When the Worker is instantiated, the URL of a script must be passed in, and this URL must be in this domain, otherwise a cross-domain error will be reported! var worker = new Worker('https://localhost/worker.js');

But you can introduce scripts in any domain through the importScripts method in worker.js, just like HTML The same as the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag in . The following are legal usage methods:

importScripts(); /* imports nothing */ importScripts(‘foo.js’); /* imports just “foo.js” */ importScripts(‘foo.js’, ‘bar.js’); /* imports two scripts */ importScripts(‘//example.com/hello.js’); /* You can import scripts from other origins */
可以利用这里的importScripts方法解决资源预加载的问题(浏览器预先加载资源,而不会对资源进行解析和执行),道理也很简单。
Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.
</script>


I believe you have mastered the methods after reading these cases. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

Implementation steps of DOM programming in html5

Using h5 to make WeChat payment process Implementation steps

#Use H5 to create a drop-down box with special effects

The above is the detailed content of How to implement Web Worker in H5 multi-threading. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn