Load JavaScript efficiently with delay and asynchrony

When loading scripts on HTML pages, you need to be careful not to damage the page's loading performance. Depending on where and how the script is added to the HTML page, it will affect the loading time

When loading scripts on HTML pages, you need to be careful not to damage the page's loading performance.

Traditionally, scripts are included in the page in the following ways:

<script src="script.js"></script>

As long as the HTML parser finds this line, it will request the script and execute the script.

Once this process is complete, the parsing can proceed, and then the rest of the HTML can be analyzed.

As you can imagine, this operation may have a huge impact on the load time of the page.

If the loading time of the script is a bit longer than expected, for example, if the network is a bit slow, or you are using a mobile device and the connection is a bit sloppy, visitors may see a blank page until the script is loaded. Load and execute.

Location is important

When you first learn HTML, the system will tell you that the script tag exists in real time<head>label:

    <script src="script.js"></script>

As I told you before, when the parser finds this line, it will fetch the script and execute it.thenAfter completing this task, it will continue to parse the body.

This is bad because it introduces a lot of delay. A very common way to solve this problem is toscriptThe label is at the bottom of the page, just before the end</body>label.

In doing so, after all pages have been parsed and loaded, the script is loaded and executed. This is aGreat progressinheadselect.

If you need an older browser that supports two relatively new features that do not support HTML, this is the best choice.asyncwithdefer.

Asynchrony and delay

Both asynchrony and delay are boolean attributes. Their usage is similar:

<script async src="script.js"></script>
<script defer src="script.js"></script>

If you specify at the same time,asyncPriority is given to modern browsers, while older browsers that support this featuredeferbut notasyncWill fall back todefer.

For support form, please visit caniuse.com for asynchronous informationhttps://caniuse.com/#feat=script-asyncAnd postponehttps://caniuse.com/#feat=script-defer

Only whenheadPart of the page, if you put the script inbodyJust like the footer we saw above.

Performance comparison

No delay or asynchrony at the head

This is how web pages load scripts without delay or asynchronously.headPart of the page:

Without defer or async, in the head

Pause parsing until the script is extracted and executed. After this operation is completed, parsing will continue.

No delay or asynchrony in the body

This is a way that there is no delay or asynchrony when the webpage loads the script, which is located inbodyLabel, just before it closes:

Without defer or async, in the body end

The parsing can be completed without any pause. After completion, the script will be extracted and executed. The parsing is done before the script download is complete, so the page is displayed before the previous example in the manner of the user.

With asynchrony, on the head

This is how the webpage loads the scriptasync, Put onheadlabel:

With async

The script is obtained asynchronously. When it is ready, HTML parsing will pause to execute the script and then resume it.

Snooze, on the head

This is how the webpage loads the scriptdefer, Put onheadlabel:

With defer

The script is obtained asynchronously and is executed only after the HTML parsing is complete.

The parsing is complete as if we put the script at the endbodyMarkup, but overall, script execution is earlier than completion because the script is downloaded at the same time as the HTML parsing.

So this is the magic weapon for speed 🏆

Prevent parsing

asyncPrevent page parsing, anddefercertainly not.

Prevent rendering

NeitherasyncnordeferMake sure to take any action when preventing rendering. It depends on you and your script (for example, make sure the script is inonLoad) Event.

dom interaction

Markup scriptdeferExecute afterdomInteractiveEvents that occur when HTML is loaded, parsed andDOMBuilt.

At this time, CSS and images still need to be parsed and loaded.

After this is done, the browser will issuedomCompleteEvent, thenonLoad.

domInteractiveIt is important because its time is considered a measure of perceived loading speed.View MDNMore.

keep the order

Another casedefer: Marked scriptasyncWhen they are available, they will be executed in random order. Markup scriptdefer(After parsing is complete) execute in the order defined in the tags.

Tell me the best way

When using scripts, the best way to speed up page loading is to put it inheadAnd add adeferAttributable to youscriptlabel:

<script defer src="script.js"></script>

This is the case that triggers fasterdomInteractiveevent.

Considered advantagesdeferSeems to be a better choiceasyncIn various situations.

Unless you can delay the first rendering of the page, make sure that the required JavaScript has been executed when the page is parsed.

Download mine for freeJavaScript beginner's manual

More browser tutorials: