HTML5 web worker

Source: Internet
Author: User

 

First, this article only discusses window. Worker and does not include sharedworker. After all, firefox4 beta7 is not supported. (It seems that newer versions of chrome safari opera are supported .) One thing to note in advance is that the Code in the worker thread has an independent execution environment. We can imagine it as a mini global environment. If you are interested, please refer to the relevant documents. In this execution environment. do not expect you to call the objects, attributes, and methods provided to us by the vast majority of hosts. you can probably think that we can only use built-in JS objects and methods. others are not considered. However, in the execution context, we can use the following things:   SELF: The globalworker object of the current worker. Some special host objects above, such as location, Navigator, setTimeout, and setinterval. The good news is that we can call JSON objects. The rest is basically some of the methods we will introduce below.   Worker has the same-origin policy restriction. That is, worker cannot introduce a cross-origin resource for direct use. (However, a worker method can bypass the same-origin policy restriction to dynamically load other domain scripts)





 Browser support:

IE: none (ie10 is supported.) Firefox: 3.5 + safair: 4 + chrome 3 + Opera: 10 + main interfaces: (you can view the detailed APIs on your own) Interface Definition link: http://www.whatwg.org/specs/web-workers/current-work/#the-workerglobalscope-abstract-interface VaR worker = new worker ('A. js ');  Outside: Event: 1. onmessage event: When a. JS is a worker thread that calls the postmessage (sdata) method, onmessage can listen to the event and execute the specified callback Method
Worker. onmessage = function (e) {e. Data // The sdata we need}
2. onerror event: capture a. js Syntax in the worker thread Exceptions and various exceptions in running and running. (Note: this is also a 404 error in loading failure. Except for Some browsers ...)  
Worker. onerror = function (e) {e. message // error message e. lineno // line number E. filename // return the URL of the complete error file .}; note: worker. addeventlistener ('message', function (e ){...}); // This is also in progress.
  Method: 1. postmessage method: send a message to the worker. The worker thread must register the onmessage event at the same time. 2. Terminate method: Stop worker.     Inside: Event: 1. onmessage event: when the worker. postmessage (sdata) method is called on the out page, onmessage can listen to the event and run the specified callback method. Method: 1. postmessage method: send a message to the out page. The out page must register the worker. onmessage event at the same time. 2. Close method: Stop worker. 3. importscripts: method used by the worker thread to dynamically load external scripts. This method will freeze the worker thread until the dynamic loading script is loaded or executed (Browser difference) . The importscripts method supports loading multiple scripts by colleagues: importscripts ('A. js', 'B. js', 'C. js '); . A colleague loads multiple scripts in each browser for parallel loading (provided that the HTTP connection count is sufficient ). But the execution order is strictly in the Parameter order. That is, execute a first, then execute B, and then C. No matter which one loads. (FF is different)  Unfortunately, safari4 initially supported worker and did not support native JSON objects. if our project does not support safari4, this is really good news. otherwise, to make the worker more robust, We need to write a JSON conversion. it is even more regrettable. browser implementation also differs greatly from some web worker behaviors. Browser differences:  Exception:In opera, a syntax error or runtime error occurs. sometimes an internal error is thrown to you. and lineno is always 0. in opera, a common syntax error or execution exception (for example, an undefined variable is called, except throw new error (s) is always unable to provide accurate error information. and lineno is always 0. in Chrome and Safari, worker. onerror does not capture the 404 exception of loading failure. chrome is a pioneer in worker. it is worth looking down on. Concerning the File Cache introduced by worker:Opera,. if Javascript is cached, it will be read directly from the cache even if it is right-clicked and loaded again. you don't have to expect 304 or 200. there is no such thing. we have two options: either completely discard the client cache, or change the version number... this is a tough issue. Differences after the close () method is calledIn opera, but the close () method is called in the worker thread. it means everything is over. if you still try to use some properties, events, or methods in worker after close ();, an internal error is thrown. but other browsers do not. in opera, the postmessage ('') that appears after the close () method is called sends information to the home page, and the onmessage callback on the home page is no longer triggered. other browsers. FF, after calling close (), the worker no longer responds to the postmessage of the page. but before close. the message sent by postmessage to the worker thread on the page. it will still be in. a callback is triggered when the worker thread ends. other Browsers Do Not. in Chrome, call close. the self object is assigned null. however, you can still directly call the workerglobalscope object method like other browsers. therefore, avoid using self. postmessage, self. onmessage = function () {}, self. close (); directly called. (For example, onmessage = function (){};) Differences after worker. Terminate () Methods In opera, after the homepage calls this method, calling worker. postmessage (sdata) will throw an exception. other browsers will not. (Although worker. postmessage is still a method at this time)   Problems caused by worker. Terminate () in Opera: 1. When a worker. onerror callback is triggered, it is triggered on the homepage not after the worker script is used to exit the execution environment. This applies to other browsers. Consider the following code:
VaR worker = new worker ("error. js"); // throw an exception. Worker. onerror = function (e ){ Alert (E); // opera will be triggered. other browsers will not. }; VaR T = new date; While (new date-T <3000 ); Worker. Terminate (); // The problem is here...
  2. The same problem exists in worker. onmessage. Consider the following code:
VaR worker = new worker ("B. JS "); // B. postmessage (sdata); worker. onmessage = function (e) {alert (E. data); // only opera triggers B. this callback in Js. and print E. data} var T = new date; while (new date-T <3000); worker. terminate ();
  The importscripts method:In ff, when the importscripts method loads the script. the current worker thread will also be frozen. however, the execution period is after the worker thread ends .. that is, this is not true for other browsers .. other browsers will freeze the worker thread. when the importscripts method loads multiple scripts in FF, the execution sequence is uncertain. it should be executed first. in FF safari chrome, when the importscripts method fails to load the script, an exception is thrown and can be thrown by the worker of the out page. onerror capture, but not in operabrowser. in ff, The importscripts method loads multiple scripts, such as. JS, B. JS, C. JS, although it is parallel loading. however, the execution will not begin until all three files a B c are loaded. 404 error for any file. will Directly exit the current execution environment and. js B. js c. JS and worker code will not be executed. this is not true for other browsers. if you use importscripts to load multiple scripts at the same time in Safari chrome, any 404 error will cause the current execution environment to exit. however, the loaded external scripts can be executed normally. opera ignores Error 404. when it does not exist. continue the subsequent tasks. Differences between creating a worker in a worker:In safari chrome, it is not allowed for worker to create a worker. ff and opera again. (that is, Safari chrome workerglobal does not have a member named worker)



 Summary: . There is no onload event for the worker object. we don't have to worry. because you have loaded it in worker. before JS is loaded, all postmessages will be triggered after the worker is loaded and executed. so we don't have to worry about this .. for cross-browser worker. we follow the logic and do not rely on the execution sequence. We can avoid some very strange problems .. you can create another worker. it is used for multi-thread parallel operation in interaction. shared communication between multiple workers and pages. see sharedworker object. browser support is still to be improved. however, worker in worer cannot cross-origin. that is, the URL of the resource referenced by the worker must be a relative path (even if the current worker script is in another domain. scripts introduced by importscripts into the outer worker. the relative path is always the path of the outside page ). or the absolute path of the same domain .. this is not supported by IE. there is no good way at the moment. It is nothing more than simulating multithreading with setTimeout. after all, we can use worker to perform large-scale operations without affecting UI update and browser interaction with users.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.