preface

In the previous article, we introduced the origin of JavaScript, which originally handled input validation in HTML pages. So how does it work in HTML as a separate language? This article describes how it is used in HTML: the

Mind mapping

This chapter focuses on

The main focus of this chapter is on the attributes of

1.<script>attribute

There are eight

crossorigin

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.

To understand Crossorigin, you first need to understand CORS. For detailed explanation of CORS, you can see this article: 15 beautiful GIFs to fully explain CORS, with a very clear explanation in the way of GIFs.

By the end of this article, you’ll no doubt know that the key to relaxing (or configuring) cross-domain requests is to include the Origin field in the request, and crossorigin does just that. As long as you have the Crossorigin attribute, the Origin header is automatically added when requesting the resource. If the response header does not have ‘access-Control-allow-origin’, it will not get the resource.

The difference between crossorigin and Crossorigin is whether or not a credential flag is set, usually a cookie. If crossorigin=”use-credentials”, cookies are taken when crossing domains.

integrity

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.

The explanation in the book is very clear, here mainly explains the encryption signature. Here, the encrypted signature format is the encryption algorithm-hash value, for example, vue:

< script SRC = "https://unpkg.com/[email protected]/dist/vue.global.js" integrity="sha384-0k9//QJdpmfSdp5IK3oJjOYPfz42f2FE0goMLtK9Vq7aKllvc4Lnz7lHPHiFhvDP" > </script>

Here sha384 is the name of the encryption algorithm followed by its hash value. If the hash value is different from the hash value of the document returned by the CDN, the CDN has probably been hacked, the file has been tampered with, and it won’t run again.

src

This is a property that you use every day, and there’s nothing special about it. A quick reminder: if you specify a value for the SRC attribute, the script tag is an external file, and js code written inside the line is ignored.

type

Type is also very simple. Generally, there are only two types of type value: one is the default plain text/javascript, and the other is the module representing ES6 module. Only in this case can the import and export keywords appear in the code.

2. Execution sequence

If there are multiple Script tags on a page, they are executed from top to bottom. But the order in which a script is executed can be affected by other situations, three of which are described in the book:

  1. defer
  2. async
  3. Dynamic writing (e.gdocument.createElement('script'))

defer

Defer means that the script is downloaded immediately, but is delayed until the entire page has been parsed.

A common performance optimization to reduce waiting time for HTML rendering (white screen time) is to put the JS script at the end of the body tag and wait until the end of the HTML sequence parsing before downloading the JS script. What is the difference between this approach and defer? Personally, I think there are two reasons:

Script tags often refer to external files. They should be placed in the header with other external files such as link, or the content representing metadata. This also prevents the developer from not seeing the JS script at the end of the document.

Second, there is a compatibility problem. Please refer to the MDN document. IE10 does not support defer until later, so considering the situation of IE8, we may still use the way of putting it at the end.

async

Async means to start downloading scripts immediately, but cannot prevent other page actions, such as downloading resources or waiting for other scripts to load.

As you can see from the above figure, if the HTML page is not parsed after the script is downloaded, the browser will pause parsing and let the JAVASCRIPT script execute first. If the HTML parsing is complete, then nothing has happened, similar to what defer did.

Like defer, it tells the browser to start downloading immediately and postpone execution, but unlike defer, scripts labeled async are not guaranteed to execute in the order in which they appear. Therefore, scripts set to Async cannot have dependencies, otherwise errors may occur.

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, such as document.write

Dynamic writing

Since JS can add script tags dynamically using the DOM API, we can actually write a script dynamically.

Of course, the request is not sent until the dynamically written script tag element is added to the DOM and executed into this code. So by default, script elements created this way are loaded asynchronously, adding an async property.

3. Performance optimization related

A common way to optimize performance is to put the JS script at the end of the body tag. This chapter also introduces optimization methods using external files, especially small componentized JS script files.

The reason for using external files is obvious: 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.

The reason for using small component-based files has to do with SPDY/HTTP2. On the initial request, if the browser supports SPDY/HTTP2, you can get a batch of files from the same place and put them one by one into the browser cache. From a browser perspective, getting all these individual resources via SPDY/HTTP2 is about the same latency as getting a large JavaScript file. But at the time of the second page request, some of the components that the second page also relies on already exist in the browser cache, because you’ve sliced the application into lightweight, cacheable files. This results in faster page loading.

conclusion

This chapter mainly introduces the method of using JavaScript in HTML: script tag.

The content of this chapter is generally combined with network related content in the interview: for example, Crossorigin is related to cross-domain; Async /defer relates to asynchronous network requests; Performance optimizations are related to browser caching and even HTTP2 features. The front end is an industry dealing with the network every day, there is still time to systematically study the computer network related content ~

Interview related articles

Script tag loading and execution time summary

Detailed introduction to the various circumstances of script tag loading and execution time, and even the little Red Book is not recommended document. Write and other situations, in fact, generally do not need to understand so deep…