Original: https://www.cnblogs.com/peakleo/p/6218823.html
--------------------------------------------------------------------------------------------------------------- --------------------------------------------
What is a Web Worker?
Web Worker is a JavaScript running in the background, does not occupy the browser itself thread, independent of other scripts, can improve the overall performance of the application, and improve the user experience.
Generally, JavaScript and UI pages share a thread, and when you execute a JS script in an HTML page, the state of the page is not responsive until the script is complete. This code can be left to the Web worker to run in the background, and the page can still respond to user actions while the JavaScript is running. A worker thread is started in the background to execute this code, and the user can create multiple worker threads.
There are two types of Web Worker
There are two types of Web workers: a dedicated thread dedicated web worker, and a shared web worker. Dedicated web worker ends with the current page closing, which means that the dedicated web worker can only be accessed by the page that created it. The shared web worker that corresponds to it can be accessed by multiple pages. In JavaScript code, the "work" type represents dedicated web worker, and the "Sharedworker" type represents a shared web worker.
In the vast majority of cases, it is sufficient to use dedicated web worker, because the code that runs in the Web worker generally is designed to serve the current page. In some specific cases, a Web worker might run a more general code that can serve multiple pages. In this case, we will create a shared web worker that shares a thread, which can be accessed by multiple pages associated with it, and the shared web worker ends only when all the associated pages are closed. The relative dedicated web worker,shared Web worker is slightly more complex.
The new Worker () object represents the dedicated web worker, and the following sample code is dedicated web worker.
How do I create a Web Worker?
Creating a new worker is straightforward. All you have to do is call the Worker()
constructor, specify a URI for the script to run within the worker thread, and if you want to be able to communicate with the worker and receive the data it passes back, you can set the worker's onmessage
property to a specific event handler when the Web The code in the event listener executes when the worker passes the message. Data from the worker is stored in the event.data.
Example.html: (Main Page):
var myworker = new Worker ("Worker_demo.js"), Myworker.onmessage = function (event) { Console.log ("Called Back by the Wo Rker!\n ");};
Alternatively, you can also use theaddEventListener()添加事件监听器:
var myworker = new Worker ("Worker_demo.js"), Myworker.addeventlistener ("message", function (event) { console. Log(+ event. Data);}, False); Myworker.postmessage ("Hello my Worker");//Start the worker.
The first line in the example creates a new worker thread. The third behavior worker sets the message
listener function for the event. When a worker calls its ownpostMessage() 函数时就会向后台Worker发送数据,并且后台返回消息调用message这个事件处理函数。
Note : Worker
The parameter URI passed into the constructor must follow the same Origin policy in order to efficiently transfer the ArrayBuffer object data, which needs to be specified in the second parameter in the PostMessage method. The instance code is as follows:
Myworker.postmessage ({ operation: ' List_all_users ', //arraybuffer object input:buffer, threshold : 0.8, }, [buffer]);
Worker_demo.js (worker):
PostMessage ("I\ ' m working before postMessage (\ ' Hello my Worker\ ')"); O nmessage = function (event) { postMessage ("Hi" + Event.data);};
Note: Typically, background threads – including worker–, cannot manipulate the DOM. if the background thread needs to modify the DOM, it should send the message to its creator, which will allow the creator to complete the operation.
With web worker you can do some small-scale distributed computing in the foreground, but web workers have some of the following usage restrictions:
- Web worker cannot access DOM nodes;
- WEB worker cannot access global variables or global functions;
- Web worker cannot access browser global variables and methods such as window and document;
However, the Web worker scope can still be used with:
- Timer-related methods SetTimeout (), cleartimeout (), setinterval () ... Functions such as
- The Navigator object, which contains the following string to identify the browser, as in the ordinary script, such as: AppName, appversion,
userAgent
...
- Introducing Scripts and libraries, the worker thread has access to a global function that
importScripts()
allows a worker to introduce a script or library into its own scope. You can introduce a URI that does not pass in a parameter or pass in multiple scripts, and the following examples are valid:
Importscripts (); /* Nothing is introduced */importscripts (' foo.js '); /* Only introduce "foo.js" */importscripts (' foo.js ', ' bar.js '); /* Introduction of two scripts */
The browser loads and runs the list of scripts. Global objects in each script can be used by the worker. If the script fails to load, an exception is thrown NETWORK_ERROR
and the next code cannot be executed. Previously executed code, including code that uses settimeout deferred execution, is still available. importScripts()
Subsequent function declarations can still be used because they will always run before other code.
Note: The download order of the scripts is not fixed, but execution will follow importScripts()
the order in which you pass the file names into. This is done synchronously, and importScripts()
will not be returned until all the scripts have been downloaded and run.
- Atob (), Btoa () base64 encoding and decoding methods.
- You can also use the XMLHttpRequest object to do Ajax communication, and other API
:WebSocket、Promise、Worker(可以在Worker中使用Worker)
下面简单写下
WEB workers use XMLHttpRequest to communicate with the server:
AddEventListener ("Message", function (evt) { var xhr = new XMLHttpRequest (); Xhr.open ("GET", "serviceurl"); Serviceurl interface for back-end J returns the son data xhr.onload = function () { postMessage (xhr.responsetext); }; Xhr.send ();},false);
The code of the above example is a bit crude, just to give a little excuse. The integration of other APIs and web workers is very similar, and you can figure it out for yourself.
Terminate web Worker
If you want to terminate a running worker immediately, you can call the worker'sterminate()方法。被终止的Worker对象不能被重启或重用,我们只能新建另一个Worker实例来执行新的任务。
Myworker.terminate ();
Handling Errors
When a worker occurs with a run-time error, its onerror
event handler is called. It receives an ErrorEvent
event that implements the interface name for error
the developer to catch the error message. The following code shows how to bind the Error event:
Worker.addeventlistener ("Error", function (evt) { alert ("line #" + Evt.lineno + "-" + Evt.message + "in" + Evt.filen AME); }, False);
As seen above, the worker object can bind the error event, and the Evt object contains the code file (evt.filename) where the error resides, the number of lines of code where the error is located (Evt.lineno), and the error message (evt.message).
The following is a complete dedicated web worker use case.
Demo_worker.html
<! DOCTYPE html>This HTML page has a Startworker button that will run a JavaScript file when clicked. The above code first detects whether the current browser supports Web Worker, and displays the reminder if it is not supported.
The button's Click event creates a Worker object and assigns it a JavaScript script file,--demo_workers.js (with code later), and binds a "message" event to the Worker object. This event is triggered when the background code (DEMO_WORKERS.JS) returns data to the page. The "message" event can be event.data to get back the data returned by the backend code. Finally, the PostMessage method formally executes the demo_workers.js, which passes the parameters to the backend code, and the background code is also obtained through the data property of the message event parameter.
Demo_worker.js
AddEventListener (' message ', function (event) { var count = event.data; var interval = setinterval (function () { postMessage (count--);! Count && clearinterval (interval); },1000);});
The above code listens to the message event in the background and gets the parameters of the page, which is actually a countdown from 10 to 1: After the message event is triggered, the result is passed to the page.
So when the Startworker button is clicked, the page will be in Count number: The display from 10 decrements to the final 1, within which the page can still respond to mouse keyboard events. Click the Stopworker button, the Web worker will be terminated directly, the page change display will stop directly.
Embedded web Worker
There is no official way to embed worker code in a Web page like a script tag. However, if a SCRIPT element is not specified src属性,并且它的
type
as a mime-type that is not specified as a running one, it is considered a block element and can be used by JavaScript. Data blocks are a very common feature in HTML5, which can carry data of almost any text type. So, you can embed a worker in the following ways:
<! DOCTYPE html>Now, the embedded worker is nested into a custom document.worker
property.
Creating a worker within a worker
One of the benefits of worker is the ability to perform processor-intensive operations without blocking the UI thread. In the example below, the worker is used to calculate the Fibonacci number.
Fibonacci.js
var results = [];function resultreceiver (event) { Results.push (parseint (Event.data)); if (results.length = = 2) { postMessage (Results[0] + results[1]);} } function Errorreceiver (event) { throw event.data;} OnMessage = function (event) { var n = parseint (event.data); if (n = = 0 | | n = = 1) { postMessage (n); return; } for (var i = 1; I <= 2; i++) { var worker = new Worker ("Fibonacci.js"); Worker.onmessage = Resultreceiver; Worker.onerror = Errorreceiver; Worker.postmessage (n-i); } };
The worker sets the property onmessage
to a function when the worker object is called postMessage()时该函数会接收到发送过来的信息。
(note that this is not the same as defining a global variable with the same name, or defining a function with the same name). var onmessage
and function onmessage
will define the same global properties as the name, but they will not register a function that can receive messages sent from a Web page created by the worker. This enables recursion, generating its own new copy to handle each loop of the calculation.
Fibonacci.html
<! DOCTYPE html>
The Web page creates an div
element with the ID, which is result
used to display the result of the operation, and then the worker is generated. After the worker is generated, the onmessage
handler is configured to div
display the result of the operation by setting the contents of the element, and finally, a message is sent to the worker to start it.
Note: Creating worker in worker and dump method under Chrome is not supported, so the above code can be run under Firefox. Due to the length of the article, the introduction of shared thread sharing web worker will be published in the next article, Web worker JavaScript multithreaded Programming (ii).
Go Web Worker JavaScript multithreaded programming (i)