+ javascript async learning and defer the execution order in javascript

A, defer and async

We used the script tag, there are two and performance, js file download execution order related properties: defer and async

 1, Defer
to defer, we can start thinking about a situation. If there is a page script outside the chain of N, on the head, then, when loading the script will block the page rendering, it is often said blank. In a simple development environment, we might as long as the external scripts location in the source code of a change ok. But, with more and more sophisticated development environment, if you want the background to develop front-end colleague colleague adjust the location of the script, you may spend a lot of communication costs and development costs. We can use defer this property.

If a script added defer property, even on the head there, it will go after the execution html page parsing is completed, which is similar to the script on the bottom of the page.

2. Async
for async, html5 this is the new property, its role is able to load and execute asynchronous script, the script does not load blocked because the page is loaded. Once loaded into will be executed immediately. That async and defer What difference is it?

async and defer marked script will not pause immediately be downloaded HTML parsing, both support the onload event callbacks to address the needs of the initialization script to execute.

3. The difference is different when performing:

async script will be executed immediately after the script file download is complete, and it performs a certain time window before the load event is triggered. This means that multiple async script execution will probably not according to their order of appearance in the pages of the order.
On the other hand, the browser ensures that multiple scripts defer the order they appear in the HTML page order execution, and the execution timing for the completion of the DOM parsing, document the DOMContentLoaded event fires before.

Let's look at the situation there async property, and defer the same, will wait for resources to load without blocking the rest of the resource, it will not affect the page is loaded. But one thing should be noted that under the circumstances when there async, js once downloaded will perform well, so you probably are not in accordance with the original order execution. If there are front and rear js-dependent, with async, it is very likely wrong. 

This article summarizes the similarities and differences between the async and defer.

Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. The defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event.

On the basis of the above, I summed up what features defer and async based on the actual usage.

Same point:

  • Page rendering is not blocked when loading files
  • For inline the script is invalid
  • You can not call document.write method script uses these two attributes of
  • There are script onload event callback

Point of difference:

  • Html4.0 html version of defined defer; html5.0 defined async
  • Browser
    Feature Chrome Firefox (Gecko) IE Opera Safari
     Basic support 1.0 1.0 (1.7 or earlier) Supported Supported Supported
    async attribute Supported 3.6 (1.9.2) 10 - 3.6 (1.9.2)
    defer attribute 3.6 (1.9.2) 3.5 (1.9.1) 4 - 3.6 (1.9.2)

In addition to the new version of the Webkit-based browser, FireFox has supported defer and onload attribute for a long time, and from FF3.6 began adding the async attribute. IE also supports defer property, but does not support async attribute, IE9 from the start, onload property will also be supported.

  • Execution time

    Each script async attribute will be executed immediately after the download is complete it, and it will be executed before the load event of the window. So there is the case of script execution order may appear to be disrupted

    Each script defer property are resolved after the page is completed, in accordance with the original order of execution, and it will be executed before the DOMContentLoaded document

There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

Simply put, using these two attributes have three possible

  • If async is true, then the script asynchronously executed after the download is complete.
  • If async is false, defer to true, then the script will be executed after the page rendering is complete.
  • If both async and defer is false, then the script parses the page, the page parsing stopped immediately downloaded and executed,
  • Finally, give a little personal advice, regardless defer or async attribute, you need to first js file page sort, which have dependencies between files, which files can be lazy loading, etc., do merge and split js code points, and then need to use these two attributes according to the page.

4, defer considerations and page optimization

Plus defer equal before the page is completely in the execution, which is equivalent window.onload, but the application is more flexible than window.onload!
defer script is a powerful function of "unsung heroes." It tells the browser Script section contains the code without the need for immediate implementation, and, used in conjunction with the SRC attribute, it can make these scripts are downloaded in the background, foreground content is normally displayed to the user.
- but the document is loaded and then execute the script

One common method is to optimize performance: when the script required to run immediately, set the "defer" attribute <SCRIPT> tag. (Not included script immediately, so the loading process will be executed in a function block.) After setting the "defer" attribute, IE does not have to wait for the completion of loading and executing the script. So pages load faster. In general, it also shows that the best placed immediately script function blocks, the function and processes the onload document object or body. In some scripts need to rely on user operation performed when ---- such as clicking a button, or move the mouse to an area ---- very useful to use the property. But there are some scripts require page load or load execution is completed, the benefits of using property derived not defer too much.

Under defer attribute default script is false of. According to DHTML programming book in the description for the Defer property it is written like this:
the Using at The attribute AT Design Time CAN Improve at The download Performance of A Page Because at The Browser does not need to the parse and the Execute at The Script and CAN the Continue Downloading and parsing at The Page instead.

In other words: If you are writing scripts added to defer attribute, the browser does not have to be handled immediately download script, but continued on page download and resolved, this will improve the performance of downloads.
There are many such cases. For example, you define a lot of javascript variable, or write a lot of scripts references (.inc) files need to be addressed, you may wish to join defer property in these scripts, improve performance certainly helps.

<script language="javascript" defer>
var object = new Object();
....
</script>

After declaring the defer attribute, we need to determine whether there are other variables cited defer the script block of variables, otherwise it will lead to script errors.

Please note two points:
1, do not call document.write command in a script block defer type, because document.write will have a direct output.
2, moreover, do not include any global variable or function to be executed immediately scripts used in the defer-type script block.

================ Description: gorgeous dividing line ===============

For work under IE znxds offered, I did a comparison for FF and IE6, IE7, IE8 below

In Firefox, inline the defer no effect; outer defer the bottom of the page will be executed.

In IE8.0, the inline and outer defer is active, the delay to the bottom will be performed later in the other non-js row of defer

The situation IE7.0, IE8.0 and consistent

IE6.0, with regard to defer inline js, to distinguish in the head or in the body. defer inline js will take precedence in the head in the face of body, and defer inline js in the body will be executed before the end of the body; About defer outer js, it is still in the implementation of the last page.

It can be seen, defer the outer js consistent performance in a variety of browsers; defer a special inline js in IE6, the order of head and body are not the same, IE7 and IE8 will be delayed until the Executive bottom of the page in Firefox invalid.

Two, JavaScript execution sequence

Js execution sequence substantially the order they appear in html, but there are some minor changes.

  1. First performed <head> tag js, whether internal or external stranded form, are performed in order of appearance.
  2. Then the script execution body, until the outer sequence <html> tag.
  3. Then perform defer = "defer" in the script. (IE test support, chrome and firefox do not support defer attribute in both browsers, the order will be executed as a normal script section).
  4. Finally, the execution body onload method b ().

Description: javaScript execution engine does not line by line analysis and implementation of the program, but for a period of analysis performed. And in the same piece of code to perform the analysis, the definition of the type function statement will be extracted precedence. After the implementation of the function definition, other code will be executed in order.

Example 1

<Script>
 var Hello = function () { 
Alert ( 'Hello, zhangsan' ); 
} 
Hello (); // first call, the output "Hello, zhangsan" 

var Hello = function () { 
Alert ( 'Hello, Lisi ' ); 
} 
Hello (); // second call, the output "Hello, Lisi" 
<Script>

Example 2

<Script type = "text / JavaScript">
     function Hello () {     
        Alert ( 'Hello, zhangsan' );     
    } 
     Hello ();   // first call, output Hello, Lisi 

    function Hello () {     
        Alert ( 'Hello, Lisi ' );     
    }     
    Hello (); // second call, output Hello, Lisi 
</ Script>

 Two calls will output the same contents "hello, lisi". The same statement is a function of two of the same name, the result is not the same Why call it?

This is due to JavaScript execution order. JavaScript execution engine does not line by line analysis and implementation program, but paragraph by paragraph analysis performed. But also in the analysis of the implementation of the same code, the definition of style function statement ( JS function is the first citizen ) always will be extracted precedence. After the implementation of the function definition, other code will be executed in order. That is, before the first call to the function hello, the first statement defines a function code has been second function definition statement code coverage, and this is why the first call hello in Example 2, will the reason behind the defined function contents output.

 Example 3

<Script type = "text / JavaScript">
     function Hello () {     
        Alert ( 'Hello, zhangsan' );     
    }     
    Hello (); // first call, output Hello, zhangsan 
</ Script> 
<Script>     function Hello ( ) {     
        Alert ( 'Hello, Lisi' );     
    } 
    Hello (); // second call, output Hello, Lisi 
</ Script>
    

  It is called twice in two different code segment, independently of each other.

reference:

Reproduced in: https: //www.cnblogs.com/JoannaQ/p/3518339.html

Guess you like

Origin blog.csdn.net/weixin_34306676/article/details/93055784