


Detailed explanation of the use of H5 multi-threading (Worker SharedWorker)
This time I will bring you a detailed explanation of the use of H5 multi-threading (Worker SharedWorker), what are the precautions when using H5 multi-threading (Worker SharedWorker), the following is a practical case, let's take a look.
There is no doubt that JavaScript does not have multi-threading. It can only do one thing one thing, and then do the next thing after finishing one thing. If your js takes a long time to do one thing, the browser will freeze for a while and not respond to the user's operations. What can you do? Thank God, HTML5 provides us with a mechanism to implement multi-threading. You must have used such a good thing before, but it doesn’t matter, let’s review it together!
1. Worker class
1. Method introduction
(1) Constructor new Worker(arg): The parameter indicates the js file where the code to be executed by your thread is located, such as 'myworker.js'. The constructor of course returns an instance of the Worker class
(2 ) worker.postMessage(message): This method means sending a message from the main thread to the sub-thread or the sub-thread sending a message to the main thread. The message is generally a string , or it can be Convert a js object into a string and send it
(3) There is also a message event on the worker. When someone sends a message to this worker instance, the event is triggered. We can get the data from his event object. Obtain the posted value in the attribute
You can see that the API of the Woker class is quite simple, with only two most commonly used methods and one event. Let's take a look at it through a practical example.
//main.html nbsp;html> <meta> <title>main</title> <p></p> <input> <button>发送</button> <script> var out = document.getElementById("out"); var btn = document.getElementById("btn"); var txt = document.getElementById("txt"); var worker = new Worker("thread1.js"); btn.addEventListener("click",function(){ var postData = txt.value; worker.postMessage(postData); },false); worker.addEventListener('message',function(e){ out.innerText = e.data; },false); </script> //thread1.js onmessage = function(event){ var res = event.data+"帅气!"; postMessage(res); }
When I enter "Big~Bear" in the text box and click the send button, the following effect will appear
Simple analysis, I am in the main thread by thead1.js creates an instance of Worker. When the button is clicked, its postMessage method is called to send the content in the text box to thread1.js. How does our thread1.js do it? That's it, it listens to the message event, and the main thread triggers the event when it sends a message, and executes the callback function. The callback function gets the value sent from the event object, and then adds "handsome!" to this value. , and then send it back. The main thread also listens to the worker's message event, so it will be triggered when a message passes, and the message content will be displayed in p, so you can see the above effect.
Perhaps you will use this for what purpose? There is really no use here. Here we can always complete the operation of adding "handsome!" in the main thread, because its complexity is O(1) (haha, I am learning algorithms recently!), but if it is not such a simple operation Woolen cloth? The advantage of this method is that no matter how complicated the work your sub-thread does, it will not stop the main thread. The main thread will continue to do whatever it is doing. Once the sub-thread has processed the data, it can just take it over. .
Teacher Lu will be able to create a new sub-thread by calling new Worker() in the sub-thread. I found that this is not possible and an undefined error will be reported, which means that the Worker construct cannot be called in the sub-thread. Function, I thought I was wrong at first, but later I checked the official documentation and found that there was no relevant description.
Let’s look at an example of calling multiple sub-threads in the main thread:
//main.html nbsp;html> <meta> <title>main</title> <p></p> <input> <button>发送</button> <script> var out = document.getElementById("out"); var btn = document.getElementById("btn"); var txt = document.getElementById("txt"); var worker1 = new Worker("thread1.js"); var worker2 = new Worker("thread2.js"); btn.addEventListener("click",function(){ var postData = txt.value; worker1.postMessage(postData); },false); worker1.addEventListener('message',function(e){ worker2.postMessage(e.data); },false); worker2.addEventListener('message',function(e){ out.innerText = e.data; },false); </script> //thread1.js onmessage = function(event){ var res = event.data+"帅气!"; postMessage(res); } //thread2.js onmessage = function(event){ var res = event.data+"没骗你哟!"; postMessage(res); close(); }
The main thread needs two threads to complete a task. It creates two threads worker1 and 2, and first calls worker1 Request, after getting the returned data, request worker2 again, and at the same time hand over the data processed by worker1 to worder2 for processing, and then get the final result and display it on the page.
In the child thread, you can introduce other js files and then call them, such as the example below.
//main.html nbsp;html> <meta> <title>main</title> <p></p> <input> <button>发送</button> <script> var out = document.getElementById("out"); var btn = document.getElementById("btn"); var txt = document.getElementById("txt"); var worker1 = new Worker("thread1.js"); btn.addEventListener("click",function(){ var postData = txt.value; worker1.postMessage(postData); },false); worker1.addEventListener('message',function(e){ out.innerText = e.data; },false); </script> //thread1.js importScripts('tools.js') onmessage = function(event){ var res = handler(event.data); postMessage(res); } //tools.js function handler(data){ return data+"加油加油!" }
You can see that our thread1.js does not have a file called tools.js, but it imports a js file through importScripts(), and then you can call the exposed methods inside.
2. SharedWorker class
The essence of SharedWorker is share. Different threads can share one thread, and their data is also shared.
Let’s discuss it directly with examples.
使用方法一:
//main.html nbsp;HTML> <title>Shared workers: demo 1</title> <p></p> <script> var worker = new SharedWorker('shared.js'); var log = document.getElementById('log'); worker.port.onmessage = function(e) { // note: not worker.onmessage! log.textContent += '\n' + e.data; } </script>
The above is the detailed content of Detailed explanation of the use of H5 multi-threading (Worker SharedWorker). For more information, please follow other related articles on the PHP Chinese website!

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor
