Why do you need asynchronous? Why? Let's see a piece of code.
Question 1:
for(var i=0;i<100000;i++){}alert('hello world!!!');This code means to execute 100 times before executing alert. The problem this brings is that it seriously blocks the execution of the subsequent code. As for why, it is mainly because JS is single-threaded.
Question 2:
We usually need to solve this problem. If we need to add script code to the head, we will generally write the code in window.onload (if the dom is operated). Have you ever thought about why we need to add window.onload ? The reason is that when you are operating the dom, the html code browser behind script has not started to load, but you think about marrying her before she was born. Is this possible? Of course it is impossible, add window. The reason why onload can be because the code in window.onload is executed after the document is fully loaded, which is equivalent to asynchronous.
Question 3:
Sometimes the page does not need to load all the code at once, but more often we only load a certain piece of code according to a certain requirement.
What is single thread?
You can understand this way that a single thread is the execution of code segments, first executing the previous one, and then executing the next one after the previous one is completed.
So which JS is asynchronous?
I believe that this thing is almost used badly. It is setTimeout/setInterval and of course Ajax. I believe everyone knows Ajax asynchronous. Of course, it can also be synchronous, but no one does it like that. However, some friends may not know differently about setTimeout and setInterval being asynchronous. Let’s talk about why setTimeout is asynchronous.
setTimeout(function(){ console.log(0);},0)console.log(1);// 1// 0 After running this code, the first prints 1 instead of 0. Are some friends beginning to be confused? Although we set the setTimeout to execute console.log(0) after 0 seconds, the setTimeout is very special because it is asynchronous. Let's put aside why the print is 1 and then 0. Let's talk about what is asynchronous.
What is asynchronous?
For example, in some restaurants, you need to make reservations in advance, and you can only go when others finish eating. Therefore, when others are eating, you can do other things. When others finish eating, someone will notify you, so you can go. For the code, such as ajax, you define a callback method. This callback method will not be executed at the time, but will wait for the server response to be completed before executing this code.
Let's go back to the previous section of setTimeout. It works like this. From the moment you define setTimeout (regardless of whether the time is 0 or not), js will not directly execute this code, but will throw it into an event queue. Only after all the synchronization tasks on the page are done, the code in the event queue will be executed. What is synchronization? Apart from asynchronous code, it is synchronization -_-.
How to implement asynchronous JS?
1. Use setTimout to achieve asynchronous
setTimeout(function(){ console.log(document.getElementByTagName('body')[0]);},0)But there is a small problem with setTimeout, which is that time is inaccurate. If you want to execute this code faster, we can use a function provided by html5.
requestAnimationFrame(function(){ console.log(document.getElementByTagName('body')[0]);})The difference between requestAnimationFrame and setTimeout is that requestAnimationFrame is executed faster than setTimeout , so many people use requestAnimationFrame to create animations.
2. Dynamically create script tags
var head = document.getElementByTagName('head')[0];var script = document.createElement('script');script.src = 'Mengzhuzi.js';head.appendChild('script');3. Use defer/async provided by script
<script src="xx.js" defer></script>
defer: This code is executed only after the page is loaded.
<script src="xx.js" async></script>
async: execute script code asynchronously
However, asynchronous is also a disadvantage, such as the following code:
Normal code:
try{ throw new Error('hello world');}catch(err){ console.log(err);}// Error: hello world(…)Asynchronous code:
try{ setTimout(function(){ throw new Error('hello world'); },0)}catch(err){ console.log(err);}// ReferenceError: setTimout is not defined(…)It can be found that the code in the catch is not executed, which means that the try cannot capture the code in the asynchronous.
Summarize
The asynchronous in JS and how to achieve this is basically over. It is a cliché about JS asynchronous, but I still hope that the content of this article will be helpful to everyone.