Chapter 2 JavaScript in HTML

In the early days of JavaScript, the folks at Netscape wanted to introduce JavaScript to HTML pages without causing the pages to render in other browsers. They eventually made some decisions and agreed to introduce common scripting capabilities to the web. Much of their work survived and eventually led to the HTML specification.

2.1 < script > element

The main way to insert JavaScript into HTML is to use <script> elements. This element was created by Netscape and was first implemented in Netscape Navigator 2. Later, this element was formally added to the HTML specification. The <script> element has the following eight attributes:

  • 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 the Content Delivery Network (CDN) does not host malicious Content.
  • language: scrap. 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. As usual, this value is always “text/javascript”. 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.

To embed inline JavaScript code, place the code directly inside the <script> element:

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

The rest of the page is not loaded or displayed until the code in the <script> element has been evaluated.

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

As with inline JavaScript, pages block when interpreting external JavaScript files. (The blocking time also includes the time to download the file)

In addition, tags that use the SRC attribute contain additional JavaScript code. If both are provided, the browser simply downloads and executes the script file, ignoring the inline code.

Whatever code is included, the browser will interpret

2.1.1 Label Position

Previously, all <script> elements were placed in the <head> tag of the page

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

Putting all the JavaScript files in there means that all the JavaScript code must be downloaded, parsed, and interpreted before the page can be rendered, which causes a significant delay in page rendering, during which the browser window is completely blank. Modern Web applications typically place all JavaScript references after the page content in the element:

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

This way, the page renders the page completely before processing the JavaScript code. The user will feel that the page loads faster.

2.1.2 Postponing script Execution

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> 
Copy the code

As mentioned earlier, the defer attribute is only valid for external script files. This is explicitly specified in HTML5, so html5-enabled browsers ignore the defer attribute of inline scripts.

Note that for XHTML documents, the defer attribute should be specified as defer=”defer”.

2.1.3 Executing the Script 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 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.

Note that for XHTML documents, the async attribute should be specified as async=”async”.

2.1.4 Dynamically Loading Scripts

Because JavaScript can use the DOM API, you can also load the specified script by dynamically adding a script element to the DOM. Just create a script element and add it to the DOM.

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

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. Performance may be severely affected. 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

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. I won’t talk too much about XHTML now that it’s gone.

2.2 Lines of code and external files

Although it is possible to embed JavaScript code directly in HTML files, it is generally considered a best practice to place JavaScript code in external files whenever possible. Here’s why:

  • Maintainability. JavaScript code spread over many HTML pages can cause maintenance difficulties. It’s easier to maintain all JavaScript files in a single directory, so developers can edit their code independently of the HTML pages that use them.
  • The cache. The browser caches all externally linked JavaScript files based on specific Settings, which means that if both pages use the same file, it only needs to be downloaded once. This ultimately means pages load faster.
  • Adapt to the future. By putting JavaScript in external files, you don’t have to worry about XHTML or the aforementioned annotation hacks. The syntax for including external JavaScript files is the same in HTML and XHTML.

2.3 Document Mode

IE5.5 invented the concept of document mode, which can be switched using DOCType. There were originally two document modes: Quirks mode and Standards Mode. With the widespread implementation of browsers, a third document mode has emerged: the Almost standards mode.

Promiscuous mode is switched on in all browsers by omitting the docTYPE declaration at the beginning of the document. This convention doesn’t make sense because promiscuous patterns vary greatly between browsers.

Standard mode is enabled through the following document type declarations:

<! -- HTML 4.01 Strict --> 
<! DOCTYPEHTML PUBLIC "- / / / / W3C DTD HTML 4.01 / / EN" 
"http://www.w3.org/TR/html4/strict.dtd"> 
<! -- XHTML 1.0 Strict --> 
<! DOCTYPEhtml PUBLIC 
"- / / / / W3C DTD XHTML 1.0 Strict / / EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<! -- HTML5 --> 
<! DOCTYPEhtml> 
Copy the code

The quasi-standard pattern is triggered by Transitional document types and Frameset document types:

<! -- HTML 4.01 Transitional --> 
<! DOCTYPEHTML PUBLIC 
"- / / / / W3C DTD HTML 4.01 Transitional / / EN" 
"http://www.w3.org/TR/html4/loose.dtd"> 
<! -- HTML 4.01 Frameset --> 
<! DOCTYPEHTML PUBLIC 
"- / / / / W3C Frameset DTD HTML 4.01 / / EN" 
"http://www.w3.org/TR/html4/frameset.dtd"> 
<! -- XHTML 1.0 Transitional --> 
<! DOCTYPEhtml PUBLIC 
"- / / / / W3C DTD XHTML 1.0 Transitional / / EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<! -- XHTML 1.0 Frameset --> 
<! DOCTYPEhtml PUBLIC 
"- / / / / W3C DTD XHTML 1.0 Frameset / / EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> 
Copy the code

The quasi-standard pattern is very close to the standard pattern and requires little differentiation. When people talk about the “standard model,” they can mean any one of these.

2.4 < noscript > element

The browser will display content contained in <noscript> in two cases:

  • Browsers do not support scripting
  • Browser support for scripts is turned off

If any of these conditions are met, the content contained in <noscript> will be rendered. Otherwise, the browser will not render the content in <noscript>.

2.5 summary

JavaScript is inserted into an HTML page through a <script> element. This element can be used to embed JavaScript code in AN HTML page, mixing it with other tags, or to import JavaScript stored in external files.

  • Without the defer and async attributes, the code contained in the
  • For scripts that do not delay execution, the browser must finish interpreting the code in the
  • 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.
  • 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.
  • Using the **