Personal Original website: http://www.phpthinking.com/archives/443
The browser must parse the Web page before it can be presented to the user. If the browser encounters an external script that is blocked by the system during parsing, it must stop parsing and download the JavaScript. Each time this happens, the browser adds a network round trip, which results in a delay in the first time the page is rendered.
Suggestions
It is recommended that you handle the JavaScript required to render the first screen area inline and have the JavaScript delay loading required to add additional functionality to the Web page until the first screen is finished sending. Note that to shorten the load time in this way, you must also optimize the CSS sending process .
Embedded with smaller JavaScript
If the external scripts are small, you can add them directly to the HTML document. Embedding smaller files in this way allows the browser to continue rendering the Web page. For example, if the HTML document looks like this:
small.js
the resources are as follows:
/* Contents of a small JavaScript file */
Then you can embed the script as follows:
This allows you to small.js
embed it in an HTML document, eliminating external requests for it.
Delay loading JavaScriptTo prevent JavaScript from blocking page loading, we recommend that you use HTML async properties when you load JavaScript. For example:
<script async src="my.js">
If your JavaScript resource is using document.write, it is unsafe to use asynchronous loading. We recommend that you rewrite the script that uses document.write to use other techniques instead.
Also, when loading JavaScript asynchronously, it is important to be cautious if your Web pages load interdependent scripts to ensure that your app loads the script in the appropriate order of dependency.
Frequently Asked Questions
What if I'm using a JavaScript library (such as jquery)?
Many JavaScript libraries, such as jquery, can be used to enhance a Web page to add additional interactivity, animation, and other effects to the page. However, most of these behaviors can be added safely after the first screen content is rendered. Consider whether the execution and loading of such javascript can be deferred until the page is loaded.
What if I use the JavaScript framework to construct a Web page?
If the content of the Web page is constructed by client-side JavaScript, you should consider whether you can embed the relevant JavaScript modules, thereby avoiding the additional network round-tripping process. Similarly, using server-side rendering can significantly improve the effect of first page loading by rendering the JS template on the server, embedding the results into HTML, and then using the client template after the app loads.
To remove JavaScript that is blocking rendering