About the loading order of html, css and js

1
2
3
4
5
6
< head  lang="en">
     < meta  charset="utf-8">
     < title ></ title >
     < link  rel="stylesheet" href="css/*.css">
     < script  src="js/*.js></ script >
</ head >

The loading order of DOM documents is from top to bottom;

1. The DOM is loaded into the link tag

The loading of the css file is parallel to the loading of the DOM, that is to say, when the css is loaded, the Dom continues to load and build, and the css style or img encountered in the process will send a request to the server, and after the resource returns , add it to the corresponding position in the dom;

2. The DOM is loaded into the script tag

Since the js file will not be loaded in parallel with the DOM, it is necessary to wait for the entire js file to be loaded before continuing to load the DOM. If the js script file is too large, it may cause the browser page to display lag and appear in a "feigned death" state. This effect Call it the "blocking effect"; it can lead to a very bad user experience;

And this feature is also why $(document).ready(function(){}) or (function(){}) or window.onload is required at the beginning of the js file, that is, the js file is executed after the DOM document is loaded. In this way, there will be no problems such as not finding DOM nodes;

The reason why js blocks the loading of other resources is that the browser needs to rebuild the DOM tree in order to prevent js from modifying the DOM tree;

3. Solution

The premise is that js is an external script;

Adding defer="ture" to the script tag will allow js and DOM to be loaded in parallel, and then execute the js file after the page is loaded, so that there is no blocking;

Add async="ture" to the scirpt tag, this attribute tells the browser that the js file is loaded and executed asynchronously, that is, it does not depend on other js and css, that is to say, the loading order of the js file cannot be guaranteed, but there are also The effect of DOM parallel loading;

When the defer and async attributes are used at the same time, the defer attribute will be invalid;

You can put the scirpt tag after the body tag so that there will be no loading conflicts.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325775694&siteId=291194637