Home > Article > Web Front-end > Introduction to HTML5 Web Worker (with examples)
This article brings you an introduction to HTML5 Web Worker (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Web Worker in the browser
Background introduction
We all know that the JavaScript language is executed in a single thread, that is to say, at the same time It can only do one thing, which has a lot to do with this language. It runs in a synchronous execution manner. If blocking occurs, the subsequent code will not be executed. HTML5 proposed the web Worker standard, which means JavaScript Multiple threads are allowed, but the sub-threads are completely controlled by the main thread. The sub-threads cannot operate the DOM. Only the main thread can operate the DOM. Therefore, the single-thread execution principle with the main thread as the main thread has become the core of the JavaScript language.
The difference between process and thread
The fundamental difference: Process is the basic unit of operating system resource allocation, while thread is the basic unit of task scheduling and execution.
In the operating system, multiple processes (programs) can be run at the same time; and in the same process (program), multiple threads can be executed at the same time.
Compatibility
To put it simply, on the basis of single-threaded execution of Javascript, a sub-thread is started to perform program processing without affecting the execution of the main thread. When the sub-thread completes execution, it returns to the main thread. , in this process it does not affect the execution process of the main thread.
Give a chestnut
Traditionally, after executing the following code, the entire page will be frozen. Since JavaScript is single-threaded, the following code has completely blocked subsequent execution
while(1){}
If we change the way, we can avoid this situation by starting a new thread to execute this code, putting it in a separate worker.js file, and executing the following code in the main thread. .
var worker = new Worker("worker.js")
Usage of Web Worker
Determine whether the current browser supports web worker
if (typeof (Worker) != "undefined") { //浏览器支持web worker if (typeof (w) == "undefined") { //w是未定义的,还没有开始计数 w = new Worker("webworker.js"); //创建一个Worker对象,利用Worker的构造函数 } //onmessage是Worker对象的properties w.onmessage = function (event) { //事件处理函数,用来处理后端的web worker传递过来的消息 // do something }; } else { // 浏览器不支持web worker // do something }
①Create a new Worker
var worker = new Worker("worker.js")
②Pass parameters
worker.postMessage()
③Receive messages
worker.onMessage = function(msg){}
④Exception handling
worker.onerror = function(err){}
⑤End worker
worker.terminate()
⑥Load tool class function
importScripts()
When we create a new worker, the code will run in a new javascript environment (WorkerGlobalScope), which is completely isolated from the script that created the worker. At this time We can call the script that creates a new worker the main thread, and the new worker created is called a child thread.
WorkerGlobalScope is the global object of the worker, so it contains all the properties owned by the core javascript global object such as JSON, etc. Some properties of the window also have properties similar to XMLHttpRequest(), etc.
But the new worker we started is the child thread, which does not support operating the DOM of the page.
There are many ways to communicate data between the main thread and sub-threads. The communication content can be text or objects. It should be noted that this communication is a copy relationship, that is, a value is passed instead of an address. Modifications of the communication content by the sub-thread will not affect the main thread. In fact, the internal operating mechanism of the browser is to serialize the communication content first, and then send the serialized string to the child thread, which then restores it.
Shared thread is to avoid duplication of threads The creation and destruction process reduces the consumption of system performance.
Shared thread SharedWorker can have multiple page thread links at the same time.
To use SharedWorker to create a shared thread, you also need to provide the URL address or Blob of a javascript script file. The script file contains the code we need to execute in the thread, as follows:
var worker = new SharedWorker("sharedworker.js");
Shared threads are also used The message event is used to monitor thread messages, but the port attribute of the SharedWorker object is used to communicate with the thread as follows:
worker.port.onmessage = function(msg){};
At the same time, we can also use the port attribute of the SharedWorker object to send messages to the shared thread as follows:
worker.port.postMessage(msg);
①当一个web worker的文档列表不为空的时候,这个web worker会被称之为许可线程。
②当一个web worker的文档列表中的任何一个对象都是处于完全活动状态的时候,这个web worker会被称之为需要激活线程。
③当一个web worker是许可线程并且拥有计数器或者拥有数据库事务或者拥有网络连接或者它的web worker列表不为空的时候,这个web worker会被称之为受保护的线程。
④当一个web worker是一个非需要激活线程同时又是一个许可线程的时候,这个web worker会被称之为可挂起线程。
1.可以加载一个JS进行大量的复杂计算而不挂起主进程,并通过postMessage,onmessage进行通信
2.可以在worker中通过importScripts(url)加载另外的脚本文件
3.可以使用 setTimeout(), clearTimeout(), setInterval(), and clearInterval()
4.可以使用XMLHttpRequest来发送请求
5.可以访问navigator的部分属性
1.不能跨域加载JS
2.worker内代码不能访问DOM
3.各个浏览器对Worker的实现不大一致,例如FF里允许worker中创建新的worker,而Chrome中就不行
4.不是每个浏览器都支持这个新特性
The above is the detailed content of Introduction to HTML5 Web Worker (with examples). For more information, please follow other related articles on the PHP Chinese website!