Look at JavaScript threads again

Source: Internet
Author: User
Tags script tag

After discussing some of the JavaScript threading knowledge, we might as well look back and see if JavaScript is not multithreaded. The following is a very simple code (demo, without considering compatibility issues):

 code judgment one:

<DivID= "Div">Click Me</Div><Script> varDiv=document.getElementById ("Div"); Div.addeventlistener ('Click',function() {alert ('You have clicked Me!'); }); for(varI=0; I<999999999; I++) {console.log (i); }</Script>

Execution, no accident all browsers will die, because the above for loop too many times, very CPU resources, and based on the fact that JavaScript single-threaded, browser UI rendering is suspended and caused by suspended animation.

Now the problem is, 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 snippet one", can write this (point I download the class library):

 Code fragment two:

<DivID= "Div">Click Me</Div><Scriptsrc= "Concurrent.Thread.js"></Script><Script>Concurrent.Thread.create (function(){ varDiv=document.getElementById ("Div"); Div.addeventlistener ('Click',function() {alert ('You have clicked Me!'); }); for(varI=0; I<9999999; I++) {console.log (i); } });</Script>

a "new thread" can be created from the Create method provided by the class library. Also, set the Type property of the script tag totext/x-script.multithreaded-js 也可以实现同样的效果:

Code Snippet Three:
<DivID= "Div">Click Me</Div><Scriptsrc= "Concurrent.Thread.js"></Script><Scripttype= "Text/x-script.multithreaded-js"> varDiv=document.getElementById ("Div"); Div.addeventlistener ('Click',function() {alert ('You have clicked Me!'); }); for(varI=0; I<9999999; I++) {console.log (i); }</Script>

Webworker

How could HTML5 be so blind to the bad user experience that the browser is stuck with?

Let's do the test with the classic Fibonacci sequence:

Code Snippet Four:

Main Page:<DivID= "Div"></Div><Script>window.onload=function(){ varDiv=document.getElementById ("Div"); if(typeof(Worker)!=="undefined") {//before creating Webworker, determine if the browser supports
Console.log ("Start calculating ....");
var time1= new Date () *1;//Gets the current timestampvarworker=NewWorker ("Fibonacci.js");//Create a Webworker object and pass the path to the script that will be executed in the new thread Worker.onmessage=function(e) {//Monitor data sent from the new line Cheng div.innerhtml=E.data;
var time2=new Date () * *;
Console.log ("Time Spend:" + (TIME2-TIME1) + "MS"); }
Worker.postmessage ( $);//Send data to new thread}Else{alert ("Your Browser don't support Webwoker"); } }</Script>Fibonacci.js:var fibonacci=function (n) {return n<3 ? N: (Arguments.callee (n-1) +arguments.callee (n-2)); }onmessage =function(e){var num=parseint (e.data,10); PostMessage (Fibonacci (num));//Send data to main page}

The basic usage has been commented out in the code, and by looking at the console, you can see that the execution time is printed quickly. So we come to the conclusion thatWebworker is suitable for performing complex computations at the front end . It is important to note that Webworker does not support cross-domain, local testing or HTTP protocol, do not use the file protocol, or you cannot create worker objects and report script errors.

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

Worker.postmessage (36);

Worker.postmessage (36);

Worker.postmessage (36);

because there is only one Webworker instance at this time, the PostMessage executes sequentially rather than asynchronously, and does not fully perform 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 jsonp the implementation of the principle is to load the data by dynamically inserting the script tag, then we try to use the webworker to achieve the same thing is not better? Because Webworker is multi-threaded, not blocking, not beautiful? But actually after the experiment, we found that webworker performance is not satisfactory. So this is not what it is good at, let's not let it someone else.

2, Webworker in the acceptance of other sources of information, in fact, the security of the site has brought a hidden danger, if the receipt of script information from unknown sources, may lead to XSS injection attacks. So this needs to be prevented, in fact, we use innerHTML in the above example is not safe, you can use innertext or modern browser provided by the Textcontent to replace, to filter out HTML tags.

  Today more tired, want to sleep, first write so much. Interested in in-depth students can view this address learn more: In-depth understanding of HTML5 worker threads

Look at JavaScript threads again

Related Article

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.