JavaScript and CSS
In Part 1 and Part 2, we have introduced several code for improving the page content and server in the website performance. In addition, JavaScript and CSS are also common content on our pages, they are also optimized to improve the performance of the website:
CSS:
1. Place the style sheet on the top
2. Avoid using CSS expressions)
3. Use external JavaScript and CSS
4. Reduce JavaScript and CSS
5. Replace @ import with <link>
6. Avoid using filters.
JavaScript
1. Place the script at the bottom of the page
2. Use external JavaScript and CSS
3. Reduce JavaScript and CSS
4. Remove duplicate scripts
5. Reduce DOM access
6. Develop intelligent event processing programs
17. Place the style sheet on the top
Studying Yahoo! When we put the style sheet in the Performance-oriented front-end servers often want to load pages 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 users who have a lot of content and who have a low network speed. Visual feedback, such as process pointers, has been well studied and formed a formal document. In our research, HTML pages are process pointers. When the browser sequentially loads the file header, navigation bar, top logo, and so on, users waiting for page loading can serve as visual feedback. This improves the user experience as a whole.
The problem with placing a style sheet at the bottom of the document is that in many browsers including Internet Explorer, this will abort the orderly presentation of the content. The browser suspends rendering to avoid page element re-painting caused by style changes. The user has to face a blank page.
The HTML specification clearly states that the style sheet should be placed in the
18. Avoid using CSS expressions)
CSS expressions are powerful but dangerous methods to dynamically set CSS attributes. Internet Explorer supports CSS expressions since version 5th. In the following example, you can use a CSS expression to change the background color every hour:
Background-color: expression (new Date (). getHours () % 2? "# B8D4FF": "# F08A00 ");
As shown above, expression uses a JavaScript expression. The CSS attribute is set based on the calculation result of the JavaScript expression. The expression method does not work in other browsers. Therefore, it is useful in cross-browser design for setting Internet Explorer separately.
The problem with expressions is that they are computed more frequently than we think. Not only when the page is displayed and scaled, but when the page is scrolling or even moving the mouse, it is re-computed. Add a counter to the CSS expression to track the computing frequency of the expression. You can easily move the mouse over 10000 times on the page.
One way to reduce the number of CSS expression computations is to use a one-time expression. It assigns the result to the specified style attribute at the first run and uses this attribute to replace the CSS expression. If the style attribute must be dynamically changed within the page cycle, it is feasible to use the event handle instead of the CSS expression. If you must use CSS expressions, remember that they must be calculated thousands of times and may affect the performance of your page.
19. Use external JavaScript and CSS
Many performance rules are about how to process external files. However, before you take these measures, you may ask a more basic question: should JavaScript and CSS be placed in external files or in the page itself?
In practical applications, using external files can increase the page speed, because JavaScript and CSS files can generate cache in the browser. The JavaScript and CSS built-in in the HTML document will be re-downloaded with the HTML document in each request. This reduces the number of HTTP requests, but increases the size of HTML documents. On the other hand, if JavaScript and CSS in external files 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 cache frequency of external JavaScript and CSS files is related to the number of requests to HTML documents. Although it is difficult, there are still some indicators that can be measured. If a user browses multiple pages on your website in a session, and these pages repeatedly use the same script and style sheet, caching external files will bring more benefits.
Many websites do not have the ability to establish these metrics. For these websites, the best way to be determined is to reference JavaScript and CSS as external files. The exception to built-in code is the website homepage, such as Yahoo! Home page and My Yahoo !. The home page has a small (maybe only once) page views in one session. You can find that the built-in JavaScript and CSS will speed up response time for end users.
For a homepage with large page views, there is a technology that balances the benefits of reducing HTTP requests brought about by built-in code and caching by using external files. One of them is built-in JavaScript and CSS on the homepage, but external files are downloaded dynamically after the page is downloaded. When these files are used on the subpage, they are cached in the browser.
20. Reduce JavaScript and CSS
Streamlining refers to reducing the file size from removing unnecessary characters from the code to save download time. During code reduction, all comments and unnecessary blank characters (spaces, line breaks, tab indentation) must be removed. In JavaScript, the size of the file to be downloaded decreases, thus saving the response time. The two most widely used tools in simplified JavaScript are JSMin and YUI Compressor. YUI Compressor can also be used to streamline CSS.
Obfuscation is another method that can be used for source code optimization. This method is more complex than streamlining and more prone to problems in the obfuscation process. In a survey of the top 10 websites in the United States, we found that streamlining can also reduce the size of the original code by 21%, while obfuscation can reach 25%. Although obfuscation can reduce code, the risk of streamlining JavaScript is lower.
In addition to external scripts and style sheet files, the <script> and <style> code blocks can also be reduced. Even if you use Gzip to compress scripts and style sheets, streamlining these files can save more than 5% of the space. As JavaScript and CSS functions and sizes increase, code reduction will benefit you.
21. Replace @ import with <link>
As mentioned above, CSS should be placed at the top to facilitate orderly loading and rendering.
In IE, @ import at the bottom of the page serves the same purpose as <link>, so it is best not to use it.
22. Avoid using filters.
The unique attribute of IE AlphaImageLoader is used to modify the translucent effect of PNG images in versions earlier than 7.0. The problem with this filter is that when the browser loads an image, it terminates the rendering of the content and freezes the browser. Each element (not just an image) is computed once, increasing memory spending. Therefore, it has many problems.
The best way to avoid using AlphaImageLoader is to use the PNG8 format, which can work well in IE. If you really need to use AlphaImageLoader, use the underline _ filter to invalidate IE7 or later versions.
23. Place the script at the bottom of the page
The problem caused by the script is that it blocks parallel download of pages. We recommend that you download up to two concurrent content for each host name in the browser. If your image is placed on multiple host names, you can download more than two files simultaneously in each parallel download. However, when the script is downloaded, the browser will not download other files at the same time, even if the host name is different.
In some cases, it may not be easy to move the script to the bottom of the page. For example, if document. write is used in the script to insert the page content, it cannot be moved down. There may be scope issues. In many cases, this problem occurs.
A commonly used alternative method is to use a latency script. The DEFER attribute indicates that the script does not contain document. write, which tells the browser to continue displaying. Unfortunately, Firefox does not support the DEFER attribute. In Internet Explorer, scripts may be delayed, but the effect will not be as expected. If the script can be delayed, it can be moved to the bottom of the page. This will make your page load faster.
24. Remove duplicate scripts
Repeated reference of JavaScript files on the same page will affect the page performance. You may think this situation is rare. A survey of the top 10 websites in the United States showed that two of them had repeated scripts. There are two major factors that lead to repeated reference of a script: team size and script quantity. If this happens, repeated scripts can cause unnecessary HTTP requests and useless JavaScript operations, which reduces website performance.
In Internet Explorer, unnecessary HTTP requests are generated, but not in Firefox. In Internet Explorer, if a script is referenced twice and cannot be cached, it will generate two HTTP requests during page loading. Real-time scripts can be cached. When a user reloads a page, additional HTTP requests are generated.
In addition to adding additional HTTP requests, multiple operation scripts also waste time. In Internet Explorer and Firefox, there is a problem of repeated JavaScript operations regardless of whether the script can be cached or not.
One way to avoid occasional two references to the same script is to use the script management module in the template to reference the script. The most common method to reference a script using the <script/> tag on an HTML page is:
<Script type = "text/javascript" src = "menu_1.0.17.js"> </script>
In PHP, you can create a method named insertScript to replace it:
<? Php insertScript ("menu. js")?>
To prevent repeated script references, other mechanisms should be used in this method to process the script, such as checking the directory to which it belongs and adding a version number to the script file name for Expire file first class.
25. Reduce DOM access
Using JavaScript to access DOM elements is slow. Therefore, to obtain more pages, you should:
• Cache relevant elements that have been accessed
• After offline node updates, add them to the document tree.
• Avoid using JavaScript to modify the page layout
For more information about this, see Julien Lecomte's article "high-performance Ajax applications" in the YUI topic ".
26. Develop intelligent event processing programs
Sometimes we will feel slow page response, because too many event handles are attached to the DOM tree element and some event sentences are frequently triggered. This is why event delegation is a good method. If you have 10 buttons in a div, you only need to append the event handle once on the div, instead of adding a handle for each button. When an event is bubbling, you can capture the event and determine which event was triggered.
You also do not have to wait for the onload event to operate the DOM tree. What you need to do is wait for the elements you want to access in the tree structure to appear. You don't have to wait until all the images are loaded.
You may want to replace onload with the DOMContentLoaded event, but you can use the onAvailable method in the YUI event application before all browsers support it.