< script > tag

Script elements are easiest to use either by embedding JS code directly into the page or by loading external script files. And because browsers are known to parse documents with scripts until the code has been downloaded and executed, Web applications now typically place the referenced JS code after the element.

So in order to solve this introduction order problem, the HTML specification provides async and defer properties on the script tag so that the document does not block when it is parsed to script.

Defer defer script

After adding the defer attribute, putting the

Let’s start with the test case:

Chrome load panel analysis

1, you can see the main processParse HTMLWill not be affected by<script>The network process will still load the script resource immediately.

2, multiple SettingsThe script of the defer propertyTag, will execute these in order<script>The content of the.

3. After the HTML is parsed,DOMContentLoadedExecute before the event is called.

Final print test verification:

Async Asynchronous script

The

Test cases:

Chrome load panel analysis

1, the DOMContentLoadedEvent firing is not affectedasyncImpact of script loading,asyncThe script will inThe load event is executed before the call.

2. Document parsing here is too fast to reflect, in factDOMContentLoadedEvent call followingasyncScript execution order is variable.

Print test verification:

The < link > tag

prefetch

Prefetch is a browser mechanism that uses idle browser time to download resources that may be needed later. Silently pull the specified document and store it in the cache after the browser has finished loading the current page.

Usage:

<link rel="prefetch" href="xxx" />
Copy the code

Test cases:

Chrome Network panel analysis

You can seelink prefetchCoffee.jpg loading request appears. Subsequent throughimg srcWhen you request coffee.jpg again, go straight throughprefetch cacheTo obtain the. So it verifies that the browser preloads resources at idle time and gets them quickly from the browser cache when they are actually used.

preload

As the name implies, preload means that you want the browser to request resources as early as possible without blocking normal onload.

Usage:

<link rel="preload" href="xxx" as="xxx"/>
Copy the code

Test cases:

Chrome Network panel analysis

You can see that the script loads early, quickly after the browser starts parsing the HTML.

Note: Preload Link must set the AS attribute to declare the type of the resource (font/image/style/script, etc.) or the browser may not load the resource correctly. The Crossorigin attribute is required for font files or cross-domain resources that can be loaded.