JavaScript in HTML

2.1 < script > element

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. Only for 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(Sharing across source resources) Settings for related requests. CORS is not used by default.

  • Defer: Optional. Indicates that there is no problem executing the script after the document has been parsed and displayed. Only for external script files;

  • Integrity: optional. Allows the docking of received resources with the specified cryptographic signature to verify sub-resource integrity (SRI, Subresource Intergrity). 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 provide malicious Content;

  • Language: Abandoned. Originally used to represent a scripting language in a code block;

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

There are two ways to use <script> : through it to embed JavaScript code directly in a web page, and through it to include external JavaScript files in a web page.

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

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

The code contained within <script> is interpreted from top to bottom, and the rest of the page is not loaded or displayed until the code within the <script> element has been evaluated.

When using inline JavaScript code, be careful not to have the string </script> in your code, because the way the browser parses the inline script determines that when it sees the string </script>, it will treat it as the closing </script> tag.

Solution: You need to escape the backslash “\” character.

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

The SRC attribute of the <script> element can be a full URL that points to a resource that is not in the same domain as the HTML page containing it:

 <script src="http://www.somewhere.com/afile.js">
 </script> 
Copy the code

When the browser parses the resource, it sends a GET request to the path specified by the SRC attribute to retrieve the resource. 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.

2.1.1 Label placeholders

The <script> element is placed in the <head> tag of the page. Cons: This means that the JavaScript code must be downloaded, parsed, and interpreted before the page can begin rendering, during which time the browser window is completely blank.

To solve this problem, iT is common to place JavaScript references after the page content in the <body> element.

2.1.2 Postponing script Execution

Defer: Set the defer attribute on the <script> element to tell the browser to download now, but execution is delayed. (HTML5 explicitly states that the defer attribute only works for external script files)

<! DOCTYPE html><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

In this example, the <script> element is not executed until the browser has parsed the closing tag.

The HTML5 specification requires that scripts be executed in the order in which they appear, with the first deferred script executed before the second deferred script (not necessarily), but both executed before the DOMContentLoaded event.

2.1.3 Executing the Script Asynchronously

Async: Similar to defer, except that scripts labeled async are not guaranteed to execute in the order in which they appear.

Adding async to a script tells the browser that it does not 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. 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.

2.1.4 Dynamically Loading Scripts

JavaScript can use the DOM API to load a specified script by dynamically adding script elements to the DOM.

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

The request is not sent until the HTMLElement element is added to the DOM and this code is executed. <script> elements created this way by default are loaded asynchronously, adding an async property.

All browsers support the createElement () method, but not all browsers support the async property. To unify the loading behavior of dynamic scripts, you can explicitly set it to synchronous loading:

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

Resources retrieved in this way are not visible to the browser preloader and can seriously affect their priority in the resource fetch queue. To let the preloader know of the existence of these dynamic request files, you can explicitly declare them in the document header:

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

Changes in XHTML

2.1.6 Obsolete Syntax

2.2 Lines of code and external files

Reasons for using external files:

Maintainability: Keeping all JavaScript files in one directory is easier to maintain, and developers can edit code independently of using their HTML pages.

Caching: The browser caches all externally linked JavaScript files based on specific Settings, meaning that if both pages use the same file, it only needs to be downloaded once.

Fit for the future: The syntax for including external JavaScript files is the same in HTML and XHTML.

2.3 Document Mode

The quasi-standard pattern is very close to the standard pattern and requires little differentiation.

2.4 < noscript > element

<noscript> elements can contain any HTML element that can appear in <body>, except <script>, and the browser will display content contained in <noscript> in two cases:

  • Browsers do not support scripting;
  • Browser support for scripts is disabled.

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

2.5 summary:

JavaScript is inserted into an HTML page through a <script> element.

  • To include a JavaScript file, you must set the SCR property to the URL of the file to include. Files can reside on the same server as web pages or in completely different domains.

  • All <script> elements are interpreted in the order in which they appear on the page. Without the defer and async attributes, the code contained in the <script> element must be interpreted in strict order.

  • For scripts that do not delay execution, the browser must finish interpreting the code in the <script> element before proceeding to render the rest of the page. To do this, you usually place the <script> element at the end of the page, after the main content and before the </body> tag.

  • You can use the defer attribute to defer executing the script until the document has been rendered. Deferred scripts are always executed in the order 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.

  • By using the <noscript> element, you can specify what to display when a script is not supported by the browser. If the browser supports and enables scripting, nothing in the <noscript> element is rendered.