Home > Web Front-end > Front-end Q&A > What impact does js and css file location have on page performance?

What impact does js and css file location have on page performance?

青灯夜游
Release: 2020-11-30 14:27:25
Original
2996 people have browsed it

The location of CSS and JS files will affect page efficiency. The js script should be placed at the bottom. If it is placed at the head, when the js is downloaded and executed, it will affect the rendering process of drawing the page; and the CSS should be placed at the top. If it is placed at the bottom, the page can be rendered gradually, but after the CSS is downloaded and parsed, , the already rendered text and images need to be redrawn according to the new style.

What impact does js and css file location have on page performance?

The location of the js script file

The js script should be placed at the bottom because the js thread and the GUI rendering thread It is a mutually exclusive relationship. If js is placed at the head, when the js is downloaded and executed, it will affect the rendering process of drawing the page. The main function of js is to handle interaction, and the interaction must first allow the page to be rendered before it can occur, so in order to ensure the user experience , try to let the page be drawn first.

Location of CSS files

CSS is one of the key factors in page rendering. (When there is external link CSS on the page,) the browser will wait for all CSS to be downloaded. And after the parsing is completed, the page is rendered. Any delays in the critical path will affect time-to-first-screen, so we need to transfer the CSS to the user's device as quickly as possible, otherwise the user will only see a blank screen (until the page is rendered).

CSS files are placed at the top because the order of placement determines the priority of downloading, and more importantly, the rendering mechanism of the browser.

css will not affect the generation of the DOM tree during the loading process, but it will affect the generation of the Render tree, which in turn affects the layout. Therefore, generally speaking, the link tag of the style needs to be placed in the head as much as possible. Because the DOM tree is parsed from top to bottom, and the css style is loaded asynchronously, in this case, parsing the body node under the DOM tree and loading the css style can be done in parallel as much as possible, speeding up the generation of the Render tree. speed.

Put the CSS at the bottom, and the page can be rendered gradually. However, after the CSS is downloaded and parsed, the text and images that have been rendered need to be redrawn according to the new style. This is a bad user experience. experience.

The impact of the location of js, css and other scripts on performance

It can be summarized in one sentence: JS is fully blocked and CSS is semi-blocked. (The word was invented by me to facilitate memory)

  • JS will block subsequent DOM parsing and the loading of other resources (such as CSS, JS or image resources).

  • CSS will not block subsequent parsing of the DOM structure, nor will it block the loading of other resources (such as images), but it will block the loading of JS files.

  • Modern browsers are very smart and will perform prefetch optimization. After the browser obtains the HTML document, it will download the resources referenced on the page in advance. (Note that it is only downloaded in advance)

From now on, I will test and explain the results of the above test:

The tested browser is Chrome, version The number is 55.0.2883.95 (64-bit)

First use Nodejs to build a simple http server:

//test.jsconst http = require('http');const fs = require('fs');const hostname = '127.0.0.1';const port = 9000;http.createServer((req, res) => {
    if(req.url === "/") {
        fs.readFile("index.html", "utf-8", function(err, data) {
            res.writeHead(200, { 'Content-Type': 'text/html' });
 		res.write(data);
 		res.end();	
	})
    }else if(req.url === "/yellow.js") {
	//延迟 5s	fs.readFile("yellow.js", "utf-8", function(err, data) {
	    res.writeHead(200, { 'Content-Type': 'text/plain' });
	    setTimeout(function () {
	    	res.write(data);
	    	res.end();
	    }, 5000);
	})
    }else if(req.url === "/blue.js") {
	//延迟 10s	fs.readFile("blue.js", "utf-8", function(err, data) {
	    res.writeHead(200, { 'Content-Type': 'text/plain' });
	    setTimeout(function () {
	    	res.write(data);
	    	res.end();
	    }, 10000);
	})
    }else if(req.url === "/red.css") {
	//延迟 15s	fs.readFile("red.css", "utf-8", function(err, data) {
	    res.writeHead(200, { 'Content-Type': 'text/css' });
	    setTimeout(function () {
	    	res.write(data);
	    	res.end();
	    }, 15000);
	})
    }else if(req.url === "/green.css") {
	//延迟 20s	fs.readFile("green.css", "utf-8", function(err, data) {
	    res.writeHead(200, { 'Content-Type': 'text/css' });
	    setTimeout(function () {
	    	res.write(data);
	    	res.end();
	    }, 20000);
	})
    }}).listen(port, hostname, () => {
  console.log('Server running at ' + hostname);});
Copy after login

Code structure of the homepage:

//index.html
nbsp;html>


    <meta>
    <meta>
    <meta>
    <title>测试浏览器渲染</title>


    <p>First Line</p>
    <script></script>
    <p>Second Line</p>
    <link>
    <p>Third Line</p>
    <script></script>
    <p>Fourth Line</p>
    <link>
    <img  alt="What impact does js and css file location have on page performance?" >
    <p>Fifth Line</p>

Copy after login

and other CSS And JS files:

//yellow.js
document.body.style.cssText = "background: yellow !important";

//blue.js
document.body.style.cssText = "background: blue !important";
Copy after login
//red.css
body {
    background:red !important;
}

//green.css
body {
    background: green !important;
}
Copy after login

Description: The download time of yellow.js and blue.js is 5s and 10s respectively, and the download time of red.css and green.css is 15s and 20s respectively.

After that, put all the files in the same directory, enter node test.js in the console, open the browser and access 127.0.0.1:9000 to access.

Let’s look at the third conclusion first: Modern browsers are very smart and will perform prefetch optimization. After the browser obtains the html document, it will download the resources referenced on the page in advance. (Note that it is only downloaded in advance)

What impact does js and css file location have on page performance?

It’s easy to understand. It can be seen from the picture: CSS, JS, and pictures are in the browser after getting the html document. The referenced resources on the page will be downloaded almost simultaneously, but the specific execution time depends on the structure of the html. Note that I am using the Chrome browser here, and other browsers may be different.

There is also a strange phenomenon. The Chrome browser sometimes prefetches img, but sometimes it does not.

Then the first rule:

JS will block subsequent DOM parsing and the loading of other resources (such as CSS, JS or image resources).

What impact does js and css file location have on page performance?

As can be seen from the above figure, when the browser parses the yellow.js line, it will wait for yellow.js to be loaded, blocking subsequent parsing of the DOM structure ( Including DOM structure, all other resources (CSS, JS, images)).

This is easy to understand:

  • JS runs in the browser and is single-threaded. Each window has a JS thread, so of course it will block subsequent DOM trees. Analyze it.

  • JS may modify the DOM structure, add styles to the DOM, etc., so this means that the subsequent loading of resources may be meaningless before the current JS loading execution is completed.

The second point:

CSS will not block subsequent parsing of the DOM structure, nor will it block the loading of other resources (such as images), but it will block the loading of JS files.

This is relatively complicated. Let me first show the picture of the test results:

What impact does js and css file location have on page performance?

From the picture we can draw the following Summary:

  • After loading yellow.js, DOM parsing will not be blocked when downloading red.css, and due to the first rule, when parsing to blue.js this When executed, it will also block subsequent DOM parsing.

  • Since we set the download time of red.css to 15s and blue.js to 10s, we can also see from the picture of the third rule above that blue.js is 10s It will be downloaded in about 15 seconds and red.css will be downloaded in about 15 seconds.

  • Finally, the page turned blue at 15 seconds, which shows that CSS blocks the loading of JS. Although subsequent JS files are downloaded in advance, they still have to wait for the previous CSS files to be loaded. It can only be executed after completion.

  • After blue.js is loaded, you can see that the download of green.css will not affect the subsequent loading of img, so it means that the download of CSS files will not affect subsequent images. Wait for other resources and DOM loading.

This is easy to understand: before the JS code is executed, the browser must ensure that all CSS styles before JS have been parsed, otherwise it will be messed up, and the previous CSS Styles may override element styles defined in JS files, which is the fundamental reason why CSS blocks subsequent JS execution.

Finally, let me explain why the background color of the final body did not turn green: because the style defined by js has a higher priority than the style defined in the CSS file, so It's not that green.css is not loaded, it's that it doesn't take effect. Just look at the picture below: (green and red styles have been crossed out)

What impact does js and css file location have on page performance?

So after knowing the above conclusion, we should As much as possible:

  • # Define styles or CSS files in the head, and should be able to respond as soon as possible when processing such requests (CDN or something), if like the above If it takes 10 seconds to request a CSS file, then not many people on your page will have the patience to wait.

  • Place the JS script file at the bottom of the body so that the DOM structure can be rendered first to avoid DOM being blocked.

  • When writing time-consuming JS code, use asynchronous loading as much as possible, such as setTimeout, ajax, etc. This is also to avoid page rendering taking too long and affecting users. experience.

Others:

As introduced above, JS will block subsequent DOM parsing and the loading of other resources (such as CSS, JS or image resources). This is without considering defer, in the case of async.

When the browser encounters the script script: (regardless of the browser's prefetch)

  1. Without defer or async, the browser will load it immediately and Execute the specified script. "Immediately" refers to before rendering the document element under the script tag. That is to say, it does not wait for subsequent loaded document elements. Of course, it must wait for the previous CSS file to be rendered.
  2. With async, the process of loading and rendering subsequent document elements will be the same as that of script.js Loading and execution occur in parallel (download asynchronously, execution synchronously).
  3. With defer, the process of loading subsequent document elements will be carried out in parallel with the loading of script.js (asynchronously ), but the execution of script.js must be completed after all elements are parsed and before the DOMContentLoaded event is fired.

From a usage perspective, it is a better optimization choice to first throw the script at the bottom of the body. This method can ensure that all other elements that are not scripts can be loaded and parsed at the fastest speed. .

The above three points can be expressed as:

What impact does js and css file location have on page performance?

The blue line represents network reading, and the red line represents execution time, both of which are for For scripts; green lines represent HTML parsing.

Summary:

  • Since prefetch exists in modern browsers, defer and async may not be of much use. They can be used as extensions to understand the script file. Placing it at the bottom of the body can achieve a very good optimization effect.

  • defer and async both load script files asynchronously.

  • Use async with caution, because it does not consider dependencies at all. It will load as long as it is downloaded. It does not consider the loading order of page styles at this time. However, it does not depend on anything. It is very suitable for scripts or scripts that are not dependent on any script. The most typical example: Google Analytics.

  • Long-running script code can be postponed using defer.

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of What impact does js and css file location have on page performance?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template