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
- Location is important
- Asynchrony and delay
- Performance comparison
- Prevent parsing
- Prevent rendering
- dom interaction
- keep the order
- Tell me the best way
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:
<html>
<head>
<title>Title</title>
<script src="script.js"></script>
</head>
<body>
...
</body>
</html>
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 toscript
The 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 progressinhead
select.
If you need an older browser that supports two relatively new features that do not support HTML, this is the best choice.async
withdefer
.
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,async
Priority is given to modern browsers, while older browsers that support this featuredefer
but notasync
Will 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 whenhead
Part of the page, if you put the script inbody
Just 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.head
Part of the page:
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 inbody
Label, just before it closes:
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 onhead
label:
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 onhead
label:
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 endbody
Markup, 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
async
Prevent page parsing, anddefer
certainly not.
Prevent rendering
Neitherasync
nordefer
Make 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 scriptdefer
Execute afterdomInteractive
Events 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 issuedomComplete
Event, thenonLoad
.
domInteractive
It is important because its time is considered a measure of perceived loading speed.View MDNMore.
keep the order
Another casedefer
: Marked scriptasync
When 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 inhead
And add adefer
Attributable to youscript
label:
<script defer src="script.js"></script>
This is the case that triggers fasterdomInteractive
event.
Considered advantagesdefer
Seems to be a better choiceasync
In 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:
- HTML5 provides some useful tips
- How do I make a CMS-based website work offline
- The complete guide to progressive web applications
- Extract API
- Push API guide
- Channel Messaging API
- Service staff tutorial
- Cache API guide
- Notification API guide
- Dive into IndexedDB
- Selectors API: querySelector and querySelectorAll
- Load JavaScript efficiently with delay and asynchrony
- Document Object Model (DOM)
- Web storage API: local storage and session storage
- Understand how HTTP cookies work
- History API
- WebP image format
- XMLHttpRequest (XHR)
- In-depth SVG tutorial
- What is the data URL
- Roadmap for learning network platforms
- CORS, cross-domain resource sharing
- Network worker
- requestAnimationFrame() guide
- What is Doctype
- Use DevTools console and console API
- Speech Synthesis API
- How to wait for DOM ready event in pure JavaScript
- How to add classes to DOM elements
- How to traverse DOM elements from querySelectorAll
- How to remove classes from DOM elements
- How to check if a DOM element has a class
- How to change the DOM node value
- How to add the click event to the list of DOM elements returned from querySelectorAll
- WebRTC, real-time Web API
- How to get the scroll position of an element in JavaScript
- How to replace DOM elements
- How to only accept images in the input file field
- Why use the preview version of the browser?
- Blob object
- File object
- FileReader object
- FileList object
- ArrayBuffer
- ArrayBufferView
- URL object
- Type array
- DataView object
- BroadcastChannel API
- Streams API
- FormData object
- Navigator object
- How to use the geolocation API
- How to use getUserMedia()
- How to use the drag and drop API
- How to scroll on a web page
- Processing the form in JavaScript
- Keyboard events
- Mouse event
- Touch event
- How to remove all children from DOM element
- How to create HTML attributes using raw Javascript
- How to check if the checkbox is checked using JavaScript?
- How to copy to clipboard using JavaScript
- How to disable buttons using JavaScript
- How to make a page editable in the browser
- How to use URLSearchParams to get query string value in JavaScript
- How to delete all CSS on the page at once
- How to use insertAdjacentHTML
- Safari, warning before exit
- How to add an image to the DOM using JavaScript
- How to reset the table
- How to use Google fonts