--- Chapter JavaScript Advanced Programming (third edition) second - to talk about the script tag and its load order problems, including async and defer

This article is longer, if you read the patient, I would like to thank you willing to spend time in this article, I hope you have a harvest.

Speaking fact <script>, almost out of the front end knows his role: the introduction of  JavaScrit the code. Yes, this is <script>the initial cause to be created. <script>Early, this element is created by label appears Netscape, and Netscape Navigator 2 is first implemented. Later, this element is added to the official HTML specification.

JavaScript  Netscape is inseparable from birth, JavaScript  by Netscape's Brandon Archer (Brendan Eich) a scripting language developed in 1995, JavaScript  the first version of JavaScript 1.0 in Netscape Navigator 2 implementation.

<script> Owned property

  • the async : Optional, indicates you should download the script immediately, without prejudice to other actions page, other resources such as downloading or waiting to load other scripts. Valid only for external script files.
  • charset : Optional. It represents a src attribute specified by the character code set. Since most browsers will ignore its value, so few people use this property.
  • the defer : Optional. It indicates that the script can be executed again after the delay to complete the document is parsed and displayed. Valid only for external script files. IE7 and earlier versions also support this attribute embedded script.
  • Language : Obsolete. Originally used to represent the scripting language code used (such as JavaScript, JavaScript1.2 or VBScript). Most browsers will ignore this property, so there is no need to be used again.
  • src : Optional. It represents the external file that contains the code to be executed.
  • of the type : Optional. It can be seen as an alternative language of property; represents the content type scripting language code used (also called a MIME type). Although text / javascript
    and text / ecmascript have not been recommended, but people have been using or text / javascript. In fact, the server used when transferring JavaScript file
    MIME type is usually application / x-javascript, but setting this value but may lead to type in the script is ignored. Further, the following values may also be used in non-IE browser:
    file application / JavaScript and application / ecmascript. Considering the convention and maximum browser compatibility, the current value of the type property still or
    text / javascript. However, this attribute is not required if the property is not specified, its default value is still text / javascript.
In the above attributes  async attribute is new in HTML5 attributes.

Way to introduce  JavaScript two ways

Inline form

This embodiment refers to the  html file, add a <script></scritp>tag, then the  JavaScriptcode is directly written on the inside, such as:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>script 标签</title>
  <script type="text/javascript">
    console.log('内联 JavaScript');
  </script>
</head>

<body>
  <!-- content -->
</body>

</html>

External form

The external form of  JavaScript the code written in an external file which, in the  html document by  <script> the tag  src attribute is introduced, such as:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>script 标签</title>
</head>

<body>
  <!-- content -->
  <script type="text/javascript" src="./js/01.js"></script>
</body>

</html>

Comparison of two forms of introduction

For both ways, no doubt, much better than the external form of inline form, mainly for the following aspects:

  • Maintainability : external Javascript file that can be invoked multiple pages instead of repeatedly writing on each page if there is a need to change the part, you only need to modify it in an external JavaScript code that results in work. reduced, thereby making maintenance procedures more convenient.
  • Cacheable : The browser can specifically set the cache link all external JavaScript files as required. That is, if there are two pages use the same file, then the file is downloaded only once. Therefore, the end result is the ability to speed up page loading.
  • Separation of concerns : the JavaScript encapsulated in an external .js file follows the rules of separation of concerns in general, separate HTML, CSS and JavaScript in order to make it easier for us to manipulate them and if it is more than a developer synchronization job,. In this way more convenient.

Therefore, in the future development of the way to make use of an external form of introduction JavaScript.

<script> Label load order

If you want to talk about <script> the label load order problem, we must first talk about is the position of the label, because the position of the label to JavaScripthave a very important impact for the load order.

Label location

<script> Position of the label, there are two, one is the way <head>elements inside, another is on <body> the back page content elements, the following will be introduced one by one these two forms:

<script> The label is placed <head>element in

<!DOCTYPE html>
<html>

<head>
  <title>Example HTML Page</title>
  <script type="text/javascript" src="example1.js"></script>
  <script type="text/javascript" src="example2.js"></script>
</head>

<body>
  <!-- 这里放内容 -->
</body>

</html>

This is a more traditional approach, the purpose is to put all external files (including  CSS files and  JavaScript referenced files) are placed in the same place. However, the element contains all the JavaScript files in the <head> of the document, means that you must wait for all JavaScript code is downloaded, parsed and executed is completed, you can start presenting the content of the page (the browser experience is beginning to show only when the content <body> tag). For pages that require a lot of JavaScript code, this will undoubtedly lead to significant delays browser when the page is rendered in the browser window while the delay during a blank. Obviously, this approach has obvious drawbacks, especially for the mobile terminal to now, if not more than 1s content presentation, then it would be a poor user experience. To avoid this problem, there is the following load this way.

<script> The label on <body> the back element of the page content

<!DOCTYPE html>
<html>

<head>
  <title>Example HTML Page</title>
</head>

<body>
  <!-- 这里放内容 -->
  <script type="text/javascript" src="example1.js"></script>
  <script type="text/javascript" src="example2.js"></script>
</body>

</html>

For this way, before parsing the JavaScript code is contained, the content of the page is fully rendered in the browser. The user also because of the browser window displays a blank page to shorten the time to feel the speed of speeding up the opening page

Lazy loading

<script>Each attribute is certainly designed to be useful, here we come to talk about  defer property.
HTML 4.01 for the  <script> tag defines the  defer attributes. The use of this attribute indicates that the script is in the implementation will not affect the structure of the page. That is, the script will be delayed until the entire page are parsed completely before running. Therefore, in  <script> setting the element defer property, the equivalent of telling the browser to download immediately, but deferred execution, such as:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>script 标签</title>
  <script defer="defer" type="text/javascript" src="./js/01.js"></script>
  <script defer="defer" type="text/javascript" src="./js/02.js"></script>
</head>

<body>
  <!-- content -->
  <script type="text/javascript" src="./js/03.js"></script>
</body>

</html>

In this case, although we have  <script> elements on the document  <head> element, but the script it contains will be delayed until the browser encounters  </html> the tag after the execution. HTML5 specifications script executed in the order in which they appear, so the first delay script will first execute the second delay script, and both scripts prior to  DOMContentLoaded execution event. In reality, the script will not necessarily delay the implementation of the order, not necessarily in  DOMContentLoaded the implementation of the pre-event trigger, it is best to include only a delay script.

"In reality, the script will not necessarily delay the implementation of the order will not necessarily be executed before DOMContentLoaded event trigger, it is best to delay contains only a script."  This passage is a "JavaScript Advanced Programming (third edition) "in the sentence, he tangled for a long time. I have also tried to write a few examples, but the results are fed back: If the incoming  <script> label use of  defer  property, their order of execution in the order they are introduced to the. So why the author would write this sentence yet, for personal reasons feeling is: even if  HTML5  there is such a, not necessarily all of the browser vendors will comply with this requirement, some browser vendors might not implement this specification specification, but supports  defer  property, then there will be the kind of situation described, it is to be safe, use a development  defer  is very necessary.
Another point to note is that, defer property only applies to external script files.

 defer Compatibility follows:

image description

As can be seen from the figure, some browsers do not support or in some earlier versions of the browser deferproperty, therefore, to delay the script on the bottom of the page is still the best choice.

Asynchronous loading

Having a lazy loading, then we say asynchronous loading, that the use of  asyncproperty.
HTML5 is  <scriptdefined> element  async attributes. This property is  defer property similar, are used to change the behavior of processing the script. Likewise with the  defer similar,  async it applies only to an external script file, and tells the browser to download files immediately executed immediately after the download is complete [Note: This book did not say he was executed immediately after the download is complete, bloggers discovered after read a lot of articles they all say so] . But the  deferdifference is marked as  async the script does not guarantee that they are executed in the order specified. E.g:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>script 标签</title>
  <script async type="text/javascript" src="./js/01.js"></script>
  <script async type="text/javascript" src="./js/02.js"></script>
</head>

<body>
  <!-- content -->
</body>

</html>

In the code above, it may be due to  01.js download a long time, since both  <script> tag are performed asynchronously, without disturbing each other, and therefore  02.js might precede  01.js execution. Therefore, to ensure that does not depend on each other is very important between the two. Specify the  async purpose of the property is not to wait for a page to download and execute two scripts, so the page is loaded asynchronously other content. For this reason, it is recommended not to modify the scripts asynchronously during loading  DOM.

asyncCompatibility follows:

image description

It can be seen IE9 and below do not support the  asyncproperty, therefore, to delay the script on the bottom of the page is still the best choice.

<script> Visualization is loaded label

A map will be described with <script> the tab three states ( Normal , the defer , the async to) htmlthe relationship of the loading:
image description

绿色代表html解析,灰色代表html解析停止,紫色代表script下载,粉红色代表script执行。从上图很容易的看出来只要执行script,html就会停止渲染,除此之外也可以清晰的看出他们之间的加载关系。

小结

  • 所有 <script> 标签引进的 JavaScript 会按照他们引入的顺序依次被解析,在没有使用 defer 或者 async 的情况下,只有在解析完前面 <script> 元素中的代码之后,才会开始解析后面 <script> 元素中的代码。
  • 由于浏览器会先解析完不使用 defer 属性的 <script> 元素中的代码,然后再解析后面的内容,所以一般应该把 <script> 元素放在页面最后,即主要内容后面, </body> 标签前面。
  • 使用 defer 属性可以让脚本在文档完全呈现之后再执行,延迟脚本总是按照指定它们的顺序执行。
  • 使用 async 属性可以表示当前脚本不必等待其他脚本,也不必阻塞文档呈现。不能保证异步脚本按照它们在页面中出现的顺序执行。

结束语

This article is recently read "JavaScript Advanced Programming (third edition)" after writing. Now read this book you will notice that there are really a lot of fun, the fun comes in you can go deeper understanding  JavaScript, derived from the original you can use this knowledge to look so thorough, you probably derived from really been interested in such a language. In fact, I githubcreated on a warehouse, users record themselves reading the book after some knowledge of some understanding, be read the notes, it would not be encouraged to adhere to their own carefully read this book, about the resistance inherent laziness If you want a deeper understanding about  JavaScriptthe language, you can click here , everyone in the githubstudy. Finally, if the article does not have a place to write you also want to point out heavyweights.

Published 33 original articles · won praise 50 · views 20000 +

Guess you like

Origin blog.csdn.net/include_645829461/article/details/104546062