Another talk on JavaScript threading _javascript Tips

Source: Internet
Author: User

Code Judgment One:

<div id= "div" >
  click me
</div>

<script>
  var div=document.getelementbyid ("div");
  Div.addeventlistener (' click ', Function () {
   alert (' You have clicked me! ');
  };
  for (var i =0; i<999999999;i++) {
   console.log (i);
  }
</script>

Execute it, no surprises. All browsers will die because there are too many for loops, very CPU intensive, and based on JavaScript single-threaded facts, browser UI rendering is suspended and causes death.

Now the problem, I just want to implement the above code, how to do?

Concurrent.Thread.js
The class library essentially uses settimeout to implement a "fake multithreading". Before the advent of HTML5 Webworker was a good choice. For example, we want to implement the above "code fragment One", you can write this (point I download class library):

Code fragment Two:

<div id= "div" >
  click me
</div>
<script src= "Concurrent.Thread.js" ></script>
<script>
  Concurrent.Thread.create (function () {
    var Div=document.getelementbyid ("div");
    Div.addeventlistener (' click ', Function () {
     alert (' You have clicked me! ');
    };
    for (var i =0; i<9999999;i++) {
     console.log (i);
    }
  });
</script>

The Create method provided with this class library creates a "new thread". In addition, setting the Type property of the script label to Text/x-script.multithreaded-js can also achieve the same effect:

Code fragment Three:

<div id= "div" >
  click me
</div>
<script src= "Concurrent.Thread.js" ></script>
<script type= "Text/x-script.multithreaded-js" >
    var div=document.getelementbyid ("div");
    Div.addeventlistener (' click ', Function () {
     alert (' You have clicked me! ');
    };
    for (var i =0; i<9999999;i++) {
     console.log (i);
    }
</script>

Webworker
How can HTML5 be blind to the bad user experience of the above browsers?

Here's what we'll do with the classic Fibonacci series:

Code fragment Four:

Main Page:

 <div id= "div" ></div> <script> window.onload=function () {var div=d
     Ocument.getelementbyid ("div");
       if (typeof (Worker)!== "undefined") {//Before creating Webworker, first determine if the browser supports Console.log ("Start calculating ..."); var time1= new Date () *1;//gets the current timestamp var worker=new worker ("fibonacci.js");//creates the Webworker object and passes the path to the script that will be executed in the new thread W
         Orker.onmessage=function (e) {//monitor the data Div.innerhtml=e.data sent over from the new line Cheng;
         var time2=new Date () *1;
       Console.log ("Time Spend:" + (TIME2-TIME1) + "MS");
     Worker.postmessage (36);//Send data to new thread}else{alert ("Your browser does not support Webwoker"); } </script> Fibonacci.js:var fibonacci=function (n) {return n<3?n: (Arguments.callee (n-1) +arguments.call
EE (n-2));
  } onmessage=function (e) {var num=parseint (e.data,10); PostMessage (Fibonacci (num));//Send Data to Home page} 

The basic use method has been commented in the code, view the console, you can see quickly print out the execution time. So we come to the conclusion that Webworker is suitable for performing a large number of complex computations on the front end. It should be noted that Webworker does not support Cross-domain, local testing or HTTP protocol, do not use the file protocol, or you cannot create a worker object and report a script error.

If we need to perform multiple postmessage operations in succession, it is best not to write work.postmessage all the time, like this:

    Worker.postmessage ();

    Worker.postmessage ();

    Worker.postmessage (36);

Because there is only one Webworker instance at this time, PostMessage executes sequentially rather than asynchronously, and does not give full play to its performance. You can send data by creating multiple Webworker instances.

A few things to note are:

1, we observed that webworker by accepting a URL to create a worker, and the principle of JSONP is to dynamically insert the script tags to load data, then we try to use Webworker to achieve the same thing is not better? Because Webworker is multi-threaded, not blocked, not beautiful? But actually after the experiment, we found that webworker performance is not satisfactory. So this is not what it is good at, we still do not let it take over the good.

2, Webworker in the acceptance of other sources of information, but also to the site's security has brought hidden dangers, if the receipt of unknown source script information, may lead to XSS injection attacks. So this need to guard against, in fact, we use the innerHTML in the above example is not safe, can use innertext or modern browser provided textcontent to replace, to filter out HTML tags.

Today more tired, want to sleep, write so much first.

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.