In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you what knowledge you need to understand about using Web Workers. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Introduction
Web Workers allows you to run JavaScript code in the background without blocking the web user interface. Web Workers can improve the overall performance of web pages and enhance the user experience. There are two styles of Web Workers-dedicated Web Workers and shared Web Workers. This article discusses seven key aspects of Web worker that you need to know to help you decide to use them in your application.
1.Web Workers allows you to run JavaScript code in the background
Typically, the JavaScript code you write in the Web page executes in the same thread as the user interface. This is why the user interface of the web page freezes when you click a button that triggers a lengthy process. You will not be able to work in the user interface unless the processing is complete. Web worker allows you to execute JavaScript in the background so that the user interface remains responsive, even if some scripts are being executed at the same time. The background thread that executes the script is often referred to as worker thread or worker. You can generate as many worker as you want. You can also pass the data to the script being executed in worker thread and return the value to the main thread when it is finished. However, Web Workers has some limitations, as follows:
Web Workers cannot access the DOM element from the web page.
Web Workers cannot access global variables and JavaScript functions from the web page.
Web Workers cannot call the alert () or confirm () function.
You cannot access objects such as windows, documents, and parent in Web Workers.
However, you can use functions such as setTimeout (), setInterval (), etc. You can also use the XMLHttpRequest object to make an Ajax request to the server.
There are two types of 2.Web Workers
There are two types of Web Workers: private Web Workers and shared Web Workers. Dedicated Web Workers exists and dies along with the web page that created them. This means that a dedicated Web Workers created in a web page cannot be accessed from multiple web pages. Shared Web Workers, on the other hand, is shared among multiple web pages. The Worker class represents the private Web Workers, while the SharedWorker class represents the shared Web Workers.
In many cases, a dedicated Web Workers can meet your needs. This is because usually you need to execute a specific script for a web page in worker thread. However, sometimes you need to execute a script in worker thread, and this worker thread is common to multiple pages. In this case, instead of creating many dedicated Web Workers, one per page, you might as well use a shared Web Workers. A shared web worker created by one page can still be used on other pages. Only when all connections to it are closed can it be destroyed. Shared Web Workers is a little more complex than dedicated Web Workers.
The 3.Worker object represents the private Web Worker
Now that you know the basics of Web Workers, let's take a look at how to use dedicated Web Workers. The example discussed below assumes that you have created a Web application using your favorite development tool and added jQuery and Modernizr libraries to its Script folder. Add the HTML page to the web application and type the following code:
$(document) .ready (function () {if (! Modernizr.webworkers) {alert ("This browser doesn't support Web Workers!"); return;} $("# btnStart") .click (function () {var worker = new Worker ("scripts/lengthytask.js")) Worker.addEventListener ("message", function (evt) {alert (evt.data);}, false); worker.postMessage (10000);};})
The above HTML page contains a button (btnStart) that triggers some JavaScript processing. Notice that the page references the Modernizr and jQuery libraries. The block includes a ready () method handler, which in turn handles the click event of btnStart. The ready () handler first checks whether the browser supports web workers. This is done by using the webworkers property of Modernizr. If the browser does not support Web workers, an error message is displayed to the user.
The code then connects to btnStart's click event handler. The code for the click event handler is important because it uses the Worker object to run the script in the background. The click event handler creates a Worker object and stores it in the local variable, worker. The path to the JavaScript file to be executed in the background is passed in the constructor. You will soon create a LengthyTask.js. The code then adds an event handler for the message event of the Worker object. A message event is raised when the target script (in this case, LengthyTask.js) sends some values back to the web page. The message event handler can use the evt.data property to access the returned value. *, call the postMessage () method on the Worker object to trigger the execution of the LengthyTask.js. The postMessage () method also allows you to pass data to the target script. In this example, a number (10000) is passed to postMessage (), and postMessage () indicates the number of milliseconds that processing should last. You can pass any other data in the postMessage () call, such as a JavaScript object or string.
The LengthyTask.js file contains the code to be executed in the background, as follows:
AddEventListener ("message", function (evt) {var date = new Date (); var currentDate = null;do {currentDate = new Date ();} while (currentDate-date < evt.data); postMessage (currentDate);}, false)
The above code handles message events for worker thread. A message event is raised when the main page calls the postMessage () method on the Worker object. Message event handlers simulate lengthy processing by running some millisecond do-while loops. The number of milliseconds that this loop runs is passed from the home page (recall postMessage () discussed earlier). Therefore, evt.data returns 10000 in this example. Once the operation is completed for a long time, the code calls postMessage () to send the result back to the main page. In this case, you pass the value of currentDate (currentDate is a Date object).
If you run the main page and click the Start Processing button, you will receive alert () in 10 seconds. At the same time, the user interface of the page will not be blocked, you can perform actions such as scrolling, clicking, etc., indicating that the code from LengthyTask.js is running in the background.
4. The SharedWorker object represents the shared Web Worker
The previous example uses a dedicated Web worker. Let's convert the same example to using a shared Web worker. The shared Web worker is represented by the SharedWorker object. The following code shows a modified version of the code from the home page:
$(document) .ready (function () {if (! Modernizr.webworkers) {alert ("This browser doesn't support Web Workers!"); return;} $("# btnStart") .click (function () {var worker = new SharedWorker ("scripts/sharedlengthytask.js"); worker.port.addEventListener ("message", function (evt) {alert (evt.data);}, false); worker.port.start (); worker.port.postMessage (10000);});})
Pay attention to the code marked in bold. It creates an instance of SharedWorker and passes SharedLengthyTask.js in the constructor. You will create this file soon. The code then connects the message event handler to the port object of the SharedWorker object. The message handler function performs the same work as in the previous example. The code then calls the start () method on the port object. *, call the postMessage () method on the port object to send the data (10000) to the shared worker thread.
The SharedLengthyTask.js file contains the following code:
Var port;addEventListener ("connect", function (evt) {port = evt.ports [0]; port.addEventListener ("message", function (evt) {var date = new Date (); var currentDate = null;do {currentDate = new Date ();} while (currentDate-date < evt.data); port.postMessage (currentDate);}, false); port.start ();}, false)
The code first declares a variable named port, which stores a reference to the port object. This time I handled two events-- connect and message. The connect event is triggered when a connection is established with a shared Web worker. The connect event handler captures the evt.port [0] object and stores it in the port variable that was previously declared. Then connect the message event handler on the port object. Call the start () method of the port object to start listening for messages on that port. The message event handler is almost the same as the message event handler you wrote in the previous example, except that it is attached to the port object. In addition, postMessage () is called on the port object to send the processing result to the main page.
5. Web Workers can use XMLHttpRequest to communicate with the server
Sometimes Web Worker may need to communicate with the Web server. For example, you may need data that resides in some RDBMS to be processed by the client. To accomplish such tasks, you can use the XMLHttpRequest object to make a request to the server-side resource. The entire process of instantiating Worker objects and handling message events remains the same. However, you need to make a GET or POST request to the server-side resource. Consider the following code:
AddEventListener ("message", function (evt) {var xhr = new XMLHttpRequest (); xhr.open ("GET", "lengthytaskhandler.ashx"); xhr.onload = function () {postMessage (xhr.responseText);}; xhr.send ();}, false)
The code shown above creates an instance of the XMLHttpRequest object. It then calls the open () method and specifies that an GET request is made to the server-side resource LengthyTaskHandler.ashx, an ASP.NET generic handler. Although this example uses the ASP.NET generic handler, you can use any other server-side resource. It then handles the load event of the XMLHttpRequest object and calls postMessage (). Xhr.responseText as a parameter to postMessage (). Xhr.responseText will be the value returned by the ASP.NET generic handler as a response. Raises the load event when the request is completed.
LengthyTaskHandler.ashx contains the following code:
Namespace WebWorkersDemo {public class LengthyTaskHandler: IHttpHandler {public void ProcessRequest (HttpContext context) {System.Threading.Thread.Sleep (10000); context.Response.ContentType = "text/plain"; context.Response.Write ("Processing successful!");} public bool IsReusable {get {return false;}
As you can see, ProcessRequest () simulates some lengthy processing by calling the Sleep () method on the Thread class and blocks execution for 10 seconds. Then it returns a success message "Processing successful!" To the caller. If you run the main page after making these changes, you will find that after 10 seconds, an alert dialog box with this success message will be displayed.
6. You can use error events to catch unhandled errors
If your Web worker is doing something complex, you may need to add error handling to the main page code so that appropriate action can be taken when any unhandled errors occur in worker. This can be done by handling the error event of the Worker object. Whenever there is any unhandled error in the work thread, an error event is thrown. The following code shows how to do this:
Click (function () {var worker = new Worker ("scripts/lengthytask.js"); worker.addEventListener ("message", function (evt) {alert (evt.data);}, false); worker.addEventListener ("error", function (evt) {alert ("Line #" + evt.lineno + "-" + evt.message + "in" + evt.filename);}, false); worker.postMessage (10000);})
As you can see from the above code, the error handler has connected to the error event of the worker object. The error handler receives an event object that provides error information, such as the line number where the error occurred (evt.lineno), the error message (evt.message), and the file where the error occurred (evt.filename).
7. You can use the Terminate () method to terminate worker
Sometimes you may want to cancel the tasks that are being performed in worker. To do this, you can destroy Worker by calling its terminate () method. Once Worker is terminated, you cannot re-use it or restart it. Of course, you can always create another Worker instance and use it. Keep in mind, however, that terminate () will kill worker immediately and will not give you any machines to perform cleanup operations.
Web workers allows you to execute scripts in the background without freezing the web user interface. There are two types-private web worker and shared web worker. A dedicated web worker is created for each page, while a shared web worker share is used across multiple pages. The Worker class represents the private web worker,SharedWorker class represents the shared web worker.
The above is the knowledge that the editor needs to understand when using Web Workers for you. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.