2. JavaScript in HTML

2.1 <script>The element

The main way to insert JavaScript into HTML is to use elements that have the following eight attributes:

  1. Async: Optional. Indicates that you should start downloading the script immediately, but you cannot prevent other page actions, such as downloading resources or waiting for other scripts to load. This applies only to external script files.
  2. Charset: Optional. The code character set specified with the SRC attribute. This property is rarely used because most browsers don’t care about its value.
  3. Crossorigin: Optional. Configure CORS (Cross-source resource sharing) Settings for related requests. CORS is not used by default. Crossorigin = “anonymous” profile requests do not have to set credential flags. Crossorigin =”use-credentials” sets the credential flag, which means that outbound requests contain credentials.
  4. Defer: Optional. Indicates that the script can be deferred until the document is fully parsed and displayed. This applies only to external script files. In IE7 and earlier, you can specify this property for inline scripts as well.
  5. Integrity: optional. Allows the docking of received resources with the specified cryptographic signature to verify Subresource Integrity (SRI). If the signature of the received resource does not match the signature specified by this property, an error is reported and the script is not executed. This property can be used to ensure that the Content Delivery Network (CDN) does not host malicious Content.
  6. Language: Abandoned. Originally used to represent a scripting language (such as “JavaScript”, “JavaScript 1.2”, or “VBScript”) in a code block. Most browsers ignore this property and should never use it again.
  7. SRC: Optional. Represents an external file that contains the code to execute.
  8. Type: Optional. Instead of language, represents the content type (also known as MIME type) of the scripting language in the code block. As usual, this value is always “text/javascript”, although “text/javascript” and “text/ecmascript” are obsolete. The MIME type of a JavaScript file is usually “application/ X-javascript “, but giving type ownership can cause scripts to be ignored. Other values that work in non-IE browsers are “application/javascript” and “application/ecmascript”. If the value is module, the code is treated as an ES6 module, and only then can the import and export keywords appear in the code.

There are two ways to use

<script>
function sayHi() {
  console.log("Hi!");
}
</script>
Copy the code

Code contained within does not appear in the code. For example, the following code causes the browser to report an error:

<script>
function sayScript() {
  console.log("</script>");
}
</script>
Copy the code

The way the browser parses the inline script determines that when it sees the string , it will treat it as the closing tag. To avoid this problem, just escape the character “\” :

<script>
function sayScript() {
  console.log("<\/script>");
}
</script>
Copy the code

After this modification, the code can be fully interpreted by the browser without causing any errors. To include JavaScript in external files, you must use the SRC attribute. The value of this property is a URL to a file containing JavaScript code, such as:

<script src="example.js"></script>
Copy the code

This example loads an external file called example.js in the page. The file itself simply contains the JavaScript code to be placed between the start and end tags of the

In addition, tags. If both are provided, the browser simply downloads and executes the script file, ignoring the inline code.

2.2 Postponing script execution

HTML 4.01 defines an attribute called defer for the

<! DOCTYPEhtml>
<html>
<head>
<title>Example HTML Page</title>
<script defer src="example1.js"></script>
<script defer src="example2.js"></script>
</head>
<body>
<! -- Here is the page content -->
</body>
</html>
Copy the code

The defer attribute is valid only for external script files. This is explicitly specified in HTML5, so html5-enabled browsers ignore the defer attribute of inline scripts. IE4 to 7 shows old behavior, while IE8 and later support HTML5 defined behavior. Support for the defer attribute starts with Internet Explorer 4, Firefox 3.5, Safari 5, and Chrome 7. All other browsers ignore this property and process the script as usual. With this in mind, it’s better to put the script you want to postpone at the bottom of the page.

2.3 Executing scripts Asynchronously

HTML5 defines async properties for

<! DOCTYPEhtml>
<html>
<head>
<title>Example HTML Page</title>
<script async src="example1.js"></script>
<script async src="example2.js"></script>
</head>
<body>
<! -- Here is the page content -->
</body>
</html>
Copy the code

In this case, the second script might be executed before the first. Therefore, the point is that there is no dependency between them. The purpose of adding async to a script is to tell the browser that it doesn’t have to wait until the script has downloaded and executed before loading the page, nor does it have to wait until the asynchronous script has downloaded and executed before loading other scripts. Because of this, asynchronous scripts should not modify the DOM during loading. Asynchronous scripts are guaranteed to be executed before the page load event, but may be executed before or after DOMContentLoaded. Firefox 3.6, Safari 5, and Chrome 7 support asynchronous scripting. Using Async also tells the page that you won’t use Document.write, but good Web development practice doesn’t recommend this approach at all.

2.4 Dynamically Loading Scripts

There are other ways to load scripts besides the

let script = document.createElement('script');
script.src = 'gibberish.js';
script.async = false; // Turn off asynchronous, unified dynamic script loading behavior
document.head.appendChild(script);
Copy the code

Resources obtained in this way are not visible to the browser preloader. This can seriously affect their priority in the resource acquisition queue. Depending on how the application works and how it is used, this can have a significant impact on performance. To let the preloader know of the existence of these dynamic request files, declare them explicitly in the document header:

<link rel="preload" href="gibberish.js">
Copy the code

Conclusion:

JavaScript is inserted into an HTML page through a

  1. To include an external JavaScript file, you must set the SRC property to the URL of the file to include. Files can be on the same server as web pages, or they can be in completely different domains.
  2. all<script>Elements are interpreted in the order in which they appear on the page. Without using the defer and async properties, include the<script>The code in the element must be interpreted in strict order.
  3. For scripts that do not delay execution, the browser must finish interpreting the location<script>Element before continuing to render the rest of the page. For this reason, it is usually appropriate to put<script>The element is placed at the end of the page, after and after the main content</body>Tag before.
  4. You can use the defer attribute to defer executing the script until the document has been rendered. Deferred scripts are executed in principle in the order in which they are listed.
  5. The async property can be used to indicate that scripts do not wait for other scripts and do not block document rendering, which is asynchronous loading. Asynchronous scripts are not guaranteed to be executed in the order in which they appear on the page.
  6. Through the use of<noscript>Element to specify what to display when the browser does not support scripting. If the browser supports and enables scripting<noscript>Nothing in the element is rendered.