1 <script>The element

1.1 <script>Element introduction and attributes

The main way to insert JavaScript into HTML is to use

  • 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.

  • 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.

  • 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.

  • 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.

  • 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 a Content Delivery Network (CDN) does not serve malicious Content.

  • 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.

  • SRC: Optional. Represents an external file that contains the code to execute.

  • Type: Optional. Instead of language, represents the content type (also known as MIME type) of the scripting language in the code block. By convention, 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 this value to the type attribute can cause the script 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.

Browsers interpret

1.2 Usage Mode

1.2.1 By embedding JavaScript code directly into web pages,

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <script>
        console.log("hello world")
    </script>
    
</body>
</html>
Copy the code

Code contained within

When using inline JavaScript code, be careful not to have strings in your code</script>.

console.log("hello world")
console.log("</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 “\” :

console.log("hello world")
console.log("<\/script>")
Copy the code

1.2.2 Use it to include external JavaScript files in a web page

To include JavaScript in external files, you must use the SRC attribute. The value of this property is a URL pointing to a file containing JavaScript code

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

The jsexample.js file can be directly written JS code

By convention, external JavaScript files have a.js extension. This is not necessary because the browser does not check the extension of the included JavaScript file. This opens up the possibility of dynamically generating JavaScript code using server-side scripting languages, or translating JavaScript extensions like TypeScript or React’s JSX into JavaScript in the browser. Note, however, that the server often determines the correct MIME type for the response based on the file extension. If you don’t plan to use the.js extension, make sure the server returns the correct MIME type.

One of the most powerful and controversial features of the

When the browser parses the resource, it sends a GET request to the path specified by the SRC attribute to retrieve the resource, presumably a JavaScript file. This initial request is not restricted by the browser’s same-origin policy, but the JavaScript returned and executed is. Of course, this request is still limited by the parent page HTTP/HTTPS protocol.

However, be careful when referencing a JavaScript file that sits on someone else’s server, because malicious programmers can replace the file at any time. When you include JavaScript files for an external domain, make sure that the domain is your own or that it is a trusted source. The integrity property of the

2 Defer executing the script (the defer attribute)

HTML 4.01 defines an attribute called defer for the

Setting the defer attribute in the

<script src="jsexample1.js".defer></script>
<script src="jsexample2.js".defer></script>
Copy the code

They are not executed until the browser parses to the closing
tag. The HTML5 specification requires that scripts be executed in the order in which they appear, so the first deferred script is executed before the second deferred script, and both are executed before the DOMContentLoaded event. In practice, however, deferred scripts are not always executed sequentially or before the DOMContentLoaded event, so it is best to include only one such script.

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.

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.

Tips: For XHTML documents, the defer attribute should be specified as defer=”defer”

3 Executing scripts asynchronously (Async property)

HTML5 defines async properties for

<script src="jsexample1.js".async></script>
<script src="jsexample2.js".async></script>
Copy the code

The second script may 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 for the script to download and execute before loading the page, nor does it have to wait for the asynchronous script to download and execute 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 the DOMContentLoade.

Firefox 3.6, Safari 5, and Chrome 7 support asynchronous scripting.

Tips: For XHTML documents, the async attribute should be specified as async=”async”.

4 Dynamically load scripts

There are other ways to load scripts besides the

let script = document.createElement('script');
script.src = 'gibberish.js';
document.head.appendChild(script);
Copy the code

Of course, the request will not be sent until the HTMLElement element is added to the DOM and this code is executed. By default,

let script = document.createElement('script');
script.src = 'gibberish.js';
script.async = false;
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. , which can seriously affect 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

5 Changes in XHTML

XHTML (Extensible HyperText Markup Language) is the result of repackaging HTML as AN application of XML. Unlike HTML, using JavaScript in XHTML must specify a type attribute with a value of TEXT/JavaScript, which can be omitted in HTML. XHTML may be out of the way, but it’s possible to occasionally encounter legacy code in practice