PostMessage (send) and onmessage are widely used in HTML5. For example, WebWorkers uses this group of APIs to implement JavaScript calling between multiple threads, cross-documentmessaging implements JavaScript calling between two different domains. This article ...,.
Web Workers
Introduction to Web Workers
By 2008, W3C had developed the first HTML5 draft. HTML5 has carried more and more new features and functions. It not only enhances the performance of the Web system or Web page, but also adds support for Web application functions such as local databases. Among them, the most important one is the support for multithreading. In HTML5, the concept of Web Workers is proposed, and three main features of Web Workers are standardized: long running (response ), ideal Startup Performance and memory consumption. Web Workers allows developers to write background programs that can run for a long time without being interrupted by users, execute transactions or logic, and ensure that pages respond to users in a timely manner.
Web Workers provides a method for running scripts on Web Front-end Web pages in background processes. Once it is created, Web Workers can send a task request to the task pool through postMessage, and then return the message to the event handler specified by the creator through postMessage after execution (capture through onmessage ). The Web Workers process can process tasks without affecting the user interface. In addition, it can also use XMLHttpRequest to process I/O, but generally, background processes (including Web Workers processes) DOM cannot be operated. If you want the result processed by the background program to change the DOM, you can only process it by returning the message to the callback function of the Creator.
For more information about HTML5 browser support, refer to the website When can I use...
Use postMessage and onmessage in Web Workers
First, you need to create a new Worker instance in the JavaScript code on the client page. The parameter is the name of the JavaScript file to be run in another thread. Then listen to the onmessage event on this instance. Finally, JavaScript in the other thread can pass data between the two threads by calling the postMessage method.
List 1. Create a Worker instance in the main thread and listen to onmessage events
Test Web worker