Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to improve the performance Optimization of the Front end of javascript and css websites

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shows you how to improve the performance optimization of the front end of javascript and css websites. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

CSS performance optimization

1. Put the stylesheet on top

Now put the style sheet in the document's

< head />

The interior seems to speed up the download of the page. This is because you put the stylesheet into the

< head />

The page will be loaded and displayed step by step.

Performance-oriented front-end servers often want pages to load in an orderly manner. At the same time, we also want the browser to display the received content as much as possible. This is especially important for pages with more content and slower users. Returning visual feedback to users, such as process pointers, has been well studied and formally documented. In our study, the HTML page is the process pointer. When the browser loads the header, navigation bar, logo at the top in an orderly manner, it can be used as visual feedback for users waiting for the page to load. This improves the user experience as a whole.

The problem with putting stylesheets at the bottom of the document is that in many browsers, including Internet Explorer, this stops the orderly rendering of the content. Browsers abort rendering in order to avoid redrawing of page elements caused by style changes. The user has to face a blank page.

The HTML specification clearly indicates that the stylesheet should be included in the

< head />

Within the region: "and

< a />

Different

< link />

Can only appear in the document's

< head />

Area, although it can be used many times. Whether it causes a white screen or unstyled content, it is not worth trying. The best solution is to follow the HTML specification in the document.

< head />

Load your stylesheet inside

2. Avoid using CSS expressions (Expression)

The problem with expressions is that they are calculated more frequently than we think. It will be recalculated not only when the page is displayed and zoomed, but also when the page scrolls or even moves the mouse. Add a counter to the CSS expression to track how often the expression is evaluated. You can easily reach more than 10000 calculations by moving the mouse on the page.

One way to reduce the number of times CSS expressions are evaluated is to use an one-time expression that assigns the result to the specified style property on the first run and replaces the CSS expression with this property. If style properties must change dynamically during the page cycle, it is possible to use event handlers instead of CSS expressions. If you have to use CSS expressions, keep in mind that they have to be evaluated thousands of times and may affect the performance of your page.

3. Use external JavaScript and CSS

Many performance rules are about how to handle external files. But before you take these steps, you may ask a more basic question: should JavaScript and CSS be placed in an external file or in the page itself?

The use of external files in practical applications can improve page speed because both JavaScript and CSS files can generate caches in browsers. JavaScript and CSS built into the HTML document are re-downloaded with the HTML document on each request. This reduces the number of HTTP requests, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS in the external file are cached by the browser, the size of the HTML document can be reduced without increasing the number of HTTP requests.

The key issue is that the frequency of external JavaScript and CSS file caching is related to the number of requests for HTML documents. Although there is a certain degree of difficulty, there are still some indicators that can be measured. Caching external files is even more beneficial if users browse multiple pages on your site in a session, and the same scripts and stylesheets are repeatedly used in those pages.

For home pages with high page views, there is a technique that balances the reduction in HTTP requests from built-in code with the benefits of caching through the use of external files. One of these is built-in JavaScript and CSS in the home page, but external files are downloaded dynamically after the page has been downloaded, and when these files are used in the child page, they are cached in the browser.

4. Cut JavaScript and CSS

Streamlining refers to reducing file size by removing unnecessary characters from the code, thereby saving download time. When you subtract the code, all comments, unwanted white space characters (spaces, line breaks, tab indentation, etc.) should be removed. In JavaScript, response time is saved because the size of the file that needs to be downloaded becomes smaller. The two most widely used tools in streamlining JavaScript are JSMin and YUI Compressor. YUI Compressor can also be used to streamline CSS. In my previous article on front-end deployment, the ant+YUI Compressor address is: http://www.haorooms.com/post/ant_yuicom gadget also has the use of ant: http://www.haorooms.com/tools/ant_book/

Confusion is another method that can be used for source code optimization. This approach is more problematic than streamlining, more complex and confusing processes. A survey of the top 10 websites in the United States found that streamlining can also reduce the size of the original code by 21%, while confusion can reach 25%. Although confusion can better reduce code, there is less risk of streamlining for JavaScript.

In addition to subtracting external scripts and stylesheet files

< script>

And

< style>

Code blocks can and should be subtracted. Even if you've compressed scripts and stylesheets with Gzip, streamlining these files can still save more than 5% of space. Due to the increased functionality and size of JavaScript and CSS, subtracted code will benefit.

5. Replace @ import with

The previous best implementation mentioned that CSS should be placed at the top to facilitate orderly loading and rendering.

In IE, @ import at the bottom of the page and use the

< link>

The effect is the same, so it's best not to use it.

6. Avoid using filters

The IE unique attribute AlphaImageLoader is used to correct the translucency of PNG images displayed in version 7. 0 below. The problem with this filter is that when the browser loads the image, it terminates the rendering of the content and freezes the browser. It calculates once in every element (not just a picture), increasing memory costs, so its problems are multifaceted.

The best way to avoid using AlphaImageLoader altogether is to use the PNG8 format instead, which works well in IE. If you do need to use AlphaImageLoader, please use the underscore _ filter to make it invalid for users of versions above IE7.

Javascript performance optimization

1. Place the script at the bottom of the page

The problem with the script is that it prevents parallel downloads of the page. The HTTP/1.1 specification recommends that browsers have no more than two parallel downloads for each hostname. If your image is on more than one host name, you can download more than 2 files at the same time in each parallel download. But when you download a script, the browser does not download other files at the same time, even if the hostname is different.

In some cases, it may not be easy to move the script to the bottom of the page. For example, if [xss_clean] is used in the script to insert page content, it cannot be moved down. There may also be scope problems here. In many cases, we will encounter such problems.

A frequently used alternative is to use deferred scripts. The DEFER attribute indicates that [xss_clean] is not included in the script, which tells the browser to continue to display. Unfortunately, the DEFER attribute is not supported by Firefox. In Internet Explorer, the script may be delayed but the effect will not be what we expected. If the script can be delayed, it can be moved to the bottom of the page. This will make your page load faster.

2. Use external JavaScript and CSS

As written in css above, I listed cdn in my previous article, which can be called externally.

3. Cut JavaScript and CSS

Ditto, it is written in css

4. Eliminate duplicate scripts

Repeatedly referencing JavaScript files in the same page can affect the performance of the page. You might think this is rare. A survey of the top 10 websites in the United States shows that two of them have repeatedly quoted scripts. There are two main factors that cause a strange phenomenon in which a script is repeated: the size of the team and the number of scripts. If this is the case, repetitive scripts can lead to unnecessary HTTP requests and useless JavaScript operations, which degrades the performance of the site.

Unnecessary HTTP requests are generated in Internet Explorer, but not in Firefox. In Internet Explorer, if a script is referenced twice and it is not cacheable, it generates two HTTP requests during page loading. Instant scripts can be cached, and additional HTTP requests are generated when the user reloads the page.

In addition to adding additional HTTP requests, multiple operation scripts can be a waste of time. In Internet Explorer and Firefox, there is a problem of repeating JavaScript, regardless of whether the script is cacheable or not.

One way to avoid the occasional double reference to the same script is to use the script management module to reference the script in the template. Use in HTML pages

< script />

The most common way for tags to reference scripts is:

In PHP, you can replace it by creating a method called insertScript:

To prevent multiple references to the script, other mechanisms should also be used in this method to handle the script, such as checking the directory to which it belongs and adding a version number to the script file name for the Expire file header.

5. Reduce DOM access

Using JavaScript to access DOM elements is slow, so to get more information about the page, you should do this:

Cache relevant elements that have been accessed

Update nodes offline and then add them to the document tree

Avoid using JavaScript to modify the page layout

6. Develop intelligent event handlers

Sometimes we feel that the page is unresponsive because there are too many event handles attached to the DOM tree elements and some event sentence defects are triggered frequently. This is why using event delegation (event broker) is a good way. If you have 10 buttons in a div, you only need to attach an event handle to the div instead of adding a handle to each button. When the event bubbles, you can capture the event and determine which event is emitted.

You also don't have to wait for the onload event to happen in order to manipulate the DOM tree. All you need to do is wait for the elements you want to access to appear in the tree structure. You don't have to wait for all the images to be loaded.

Research on how to load JS,JS and where to put it

Blocking downloads of external JS

When downloading JS, all browsers block all other activities, such as downloading other resources, rendering content, and so on. It is not until the JS has finished downloading, parsing, and executing that it continues to download other resources and render content in parallel.

Some people may ask: why can't JS be downloaded in parallel like CSS and image? Here we need to briefly introduce how the browser constructs the page. When the browser receives the HTML document from the server and converts the HTML into a DOM tree in memory, if it finds that CSS or IMAGE is referenced on a node (node) in the conversion process, it will send another request to request CSS or image, and then continue to perform the following conversion without waiting for the return of request. When the request returns, You just need to put the returned content in the corresponding location in the DOM tree to OK. But when a JS is referenced, the browser sends a js request and waits for the request to return. Because the browser needs a stable DOM tree structure, and there is likely to be code in JS that directly changes the DOM tree structure, such as using [xss_clean] or appendChild, or even directly using location.href to jump, the browser needs to rebuild the DOM tree in order to prevent JS from modifying the DOM tree, so it will block other downloads and rendering.

Blocking download figure: the following figure shows the time waterfall of visiting the home page of blogjava. You can see that the first two image are downloaded in parallel, while the next two JS are blocked downloads (1 download).

Blocking downloads embedded in JS

Embedded JS refers to JS code written directly in an HTML document. As mentioned above, referencing an external JS will block subsequent resource downloads and subsequent content rendering, and how the embedded JS will block, see the following column 2 codes:

* * Code 1V. *

< div >

< ul >

< li >

Blogjava

< li >

CSDN

< li >

Haorooms blog

< li >

ABC

< li >

AAA

< ul >

< script type ="text/javascript" >

/ / cycle 5 seconds var n = Number (new Date ()); var N2 = Number (new Date ()); while ((N2-n))

< ( 6 * 1000 )){ n2 = Number( new Date()); } < div >

< ul >

< li >

MSN

< li >

GOOGLE

< li >

YAHOO

< ul >

After running, you will find that in Code 1, there is a blank on the page in the first 5 seconds, and all the pages are displayed after 5 seconds. In Code 2, blogjava,csdn and so on are displayed first in the first 5 seconds, and then MSN is displayed after 5 seconds.

You can see that embedded JS will block the presentation of all content, while external JS will only block the display of subsequent content, both ways will block the download of subsequent resources.

The problem of CSS blocking loading caused by embedded JS

How did CSS block the load? CSS could have been downloaded in parallel, when blocking loading will occur (in the test observation, CSS under IE6 is blocked loading, the following tests are performed under non-IE6):

Code 1 (CSS of a foreign server is selected here for effect):

< html xmlns ="http://www.w3.org/1999/xhtml" >

< head >

< title >

Js test

< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" />

< link type ="text/css" rel ="stylesheet" href ="http://69.64.92.205/Css/Home3.css" />

< body >

< img src ="http://www.haorooms.com/images/logo.gif" />

< br />

< img src ="http://www.haorooms.com/images/csdnindex_piclogo.gif" />

Time Falls:

Code 2 (only an empty embedded JS is added):

< head >

< title >

Js test

< meta http-equiv ="Content-Type" content ="text/html; charset=UTF-8" />

< link type ="text/css" rel ="stylesheet" href ="http://69.64.92.205/Css/Home3.css" />

< script type ="text/javascript" >

Function a () {}

< body >

< img src ="http://www.haorooms.com/images/logo.gif" />

< br />

< img src ="http://www.haorooms.com/images/csdnindex_piclogo.gif" />

Time Falls:

As can be seen from the time waterfall diagram, in Code 2, CSS and pictures are not downloaded in parallel, but wait for CSS to download the following two pictures in parallel. When CSS is followed by embedded JS, the CSS will block the download of the following resources.

One might ask, why not say that the embedded JS blocks the rest of the resources, but that the CSS is blocked? Think that we are using an empty function, parsing this empty function 1ms is enough, and the next two images are not downloaded until 1.3s after CSS has finished downloading. You can also try to put the embedded JS in front of the CSS so that there will be no blocking.

Root cause: because browsers maintain the order of css and js in html, stylesheets must be loaded and parsed before embedded JS execution. The embedded JS blocks subsequent resource loads, so the above CSS blocks downloads.

Where should embedded JS be placed?

1. Putting it at the bottom will still block all rendering, but it will not block the download of resources.

2. If the embedded JS is placed in the head, please put the embedded JS in front of the CSS.

3. Use defer

4. Do not call long-running functions in the embedded JS. If you must, you can call them with setTimeout.

The above content is how to improve the performance optimization of the front end of javascript and css websites. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report