If we simply reference the script in head or body, since it is unknown whether the DOM will be changed, the script will completely block the rendering of the page during the download and execution process.
If the script is in the middle of the head or body, it is very likely that a blank page will appear, user interaction will not be possible, and the user experience will be very poor.
Even if javascript files can be downloaded in parallel, the downloading process will affect the downloading of images and other resources.
So what we need to do first is:
Put the script tag at the bottom of the body;
Because there are additional Performance overhead, such as three-way handshake, so try to reduce HTTP requests:
Combine javascript files into one;
Load multiple files in one request javascript file
But the above does not solve our problem. A large javascript file will download the execution script for a long time. During this time, the browser cannot do other things. This requires non-blocking scripts, that is, the javascript code is loaded only after the page is loaded, that is, the script is downloaded after the load event of the window object is triggered.
defer: First we have to make sure that the script will not change the DOM, because adding it tells the browser that this script will not change the DOM and can be executed after the page is loaded. . After adding this attribute to the script tag, the file can be downloaded in parallel with other resources. IE does not support defer starting from IE10
async: The difference with defer is that it will be executed after the download is completed, but defer will not be executed until the page is loaded
That is, dynamically create a script tag and insert it into the page at the right time. We can use this method to load files as needed and also specify the script loading order.
is to obtain the script through XHR and then create a script tag in the callback function and insert it into the page
First add the script required for dynamic loading, make it as streamlined as possible, and add a function to load the script
Call the function in the script tag to load other scripts
Of course, There are also some lazy loading libraries that can be used.
The above is the detailed content of How to optimize script loading. For more information, please follow other related articles on the PHP Chinese website!