


What impact does js and css file location have on page performance?
Nov 18, 2020 pm 04:35 PMThe 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.
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);});
Code structure of the homepage:
//index.html nbsp;html> ????<meta> ????<meta> ????<meta> ????<title>測(cè)試瀏覽器渲染</title> ????<p>First?Line</p> ????<script></script> ????<p>Second?Line</p> ????<link> ????<p>Third?Line</p> ????<script></script> ????<p>Fourth?Line</p> ????<link> ????<img src="/static/imghw/default1.png" data-src="http://www.liuhaihua.cn/wp-content/uploads/2016/02/uuUFNjm.png" class="lazy" alt="What impact does js and css file location have on page performance?" > ????<p>Fifth?Line</p>
and other CSS And JS files:
//yellow.js document.body.style.cssText?=?"background:?yellow?!important"; //blue.js document.body.style.cssText?=?"background:?blue?!important";
//red.css body?{ ????background:red?!important; } //green.css body?{ ????background:?green?!important; }
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)
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).
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:
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)
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)
- 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.
- 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).
- 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:
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To change the text color in CSS, you need to use the color attribute; 1. Use the color attribute to set the text foreground color, supporting color names (such as red), hexadecimal codes (such as #ff0000), RGB values (such as rgb(255,0,0)), HSL values (such as hsl(0,100%,50%)), and RGBA or HSLA with transparency (such as rgba(255,0,0,0.5)); 2. You can apply colors to any element containing text, such as h1 to h6 titles, paragraph p, link a (note the color settings of different states of a:link, a:visited, a:hover, a:active), buttons, div, span, etc.; 3. Most

Astackingcontextisaself-containedlayerinCSSthatcontrolsthez-orderofoverlappingelements,wherenestedcontextsrestrictz-indexinteractions;itiscreatedbypropertieslikez-indexonpositionedelements,opacity

In web development, the choice of CSS units depends on design requirements and responsive performance. 1. Pixels (px) are used to fix sizes such as borders and icons, but are not conducive to responsive design; 2. Percentage (%) is adjusted according to the parent container, suitable for streaming layout but attention to context dependence; 3.em is based on the current font size, rem is based on the root element font, suitable for elastic fonts and unified theme control; 4. Viewport units (vw/vh/vmin/vmax) are adjusted according to the screen size, suitable for full-screen elements and dynamic UI; 5. Auto, inherit, initial and other values are used to automatically calculate, inherit or reset styles, which helps to flexibly layout and style management. The rational use of these units can improve page flexibility and responsiveness.

Backdrop-filter is used to apply visual effects to the content behind the elements. 1. Use backdrop-filter:blur(10px) and other syntax to achieve the frosted glass effect; 2. Supports multiple filter functions such as blur, brightness, contrast, etc. and can be superimposed; 3. It is often used in glass card design, and it is necessary to ensure that the elements overlap with the background; 4. Modern browsers have good support, and @supports can be used to provide downgrade solutions; 5. Avoid excessive blur values and frequent redrawing to optimize performance. This attribute only takes effect when there is content behind the elements.

The style of the link should distinguish different states through pseudo-classes. 1. Use a:link to set the unreached link style, 2. a:visited to set the accessed link, 3. a:hover to set the hover effect, 4. a:active to set the click-time style, 5. a:focus ensures keyboard accessibility, always follow the LVHA order to avoid style conflicts. You can improve usability and accessibility by adding padding, cursor:pointer and retaining or customizing focus outlines. You can also use border-bottom or animation underscore to ensure that the link has a good user experience and accessibility in all states.

Use text-align:center to achieve horizontal centering of text; 2. Use Flexbox's align-items:center and justify-content:center to achieve vertical and horizontal centering; 3. Single-line text can be vertically centered by setting line-height equal to the container height; 4. Absolute positioning elements can be combined with top: 50%, left: 50% and transform:translate (-50%, -50%) to achieve centering; 5. CSSGrid's place-items:center can also achieve dual-axis centering at the same time. It is recommended to use Flexbox or Grid first in modern layouts.

User agent stylesheets are the default CSS styles that browsers automatically apply to ensure that HTML elements that have not added custom styles are still basic readable. They affect the initial appearance of the page, but there are differences between browsers, which may lead to inconsistent display. Developers often solve this problem by resetting or standardizing styles. Use the Developer Tools' Compute or Style panel to view the default styles. Common coverage operations include clearing inner and outer margins, modifying link underscores, adjusting title sizes and unifying button styles. Understanding user agent styles can help improve cross-browser consistency and enable precise layout control.

Use the border attribute to set the dashed style to quickly create dotted lines, such as border-top:2pxdashed#000; 2. You can customize the appearance of the dotted line by adjusting the border width, color and style; 3. When applying the dotted line to dividers or inline elements, it is recommended to set height:0 or reset the default style of hr; 4. If you need to accurately control the length and spacing of the dotted line, you should use background-image and linear-gradient to cooperate with linear-gradient, for example, background:linear-gradient(toright, black33%, transparent33%) repe
