Document directory
- Optimized Loading Sequence
- JavaScript and CSS should be put in a separate file for reference instead of inline
- Reduce JS/CSS file size
- Reduce Dom operations
- Develop more flexible event handling
- Try to put the style in the head, regardless of the inner and referenced style.
- Use a valid CSS Selector
- Do not use CSS expressions
- Avoid using Filters
- Avoid @ import
- Image Optimization
- Always specify document types and character sets and ensure they are correct
- Enable gzip Compression
- Reduce request data
- Use the get Method for Ajax requests
- Early output buffer
- Use CDN
- Optimization for mobile devices
Last article: speeding up your web site front-end performance optimization rules (1)
---------------------------------------------------------------------------
Optimized Loading Sequence
As mentioned above, whether it is pre-loading or delayed loading, it is actually part of the loading sequence. Here we will talk about the loading sequence before the onload of the page.
In fact, one of the main reasons is the policy of almost all browsers when processing JS: Because JS files may change the page content and layout, therefore, when the browser encounters a script tag, it will delay the rendering of the subsequent content until the Javascript file is downloaded, parsed, and executed.
Therefore, we should try to put JS references at the bottom of the page and inline scripts to the bottom for execution.
In fact, sometimes we use document. Write to output <SCRIPT…> Label reference external JS, first of all, this does allow external js to download and parse, and will not block the resolution of the following content, but we need to know the document. write itself is a piece of JS Code, and its execution will also generate the above mentioned problems.
In addition, for example, we can add defer and ansyc to download, parse, and execute page JS without blocking the parsing of page content. like write, the JS parsing and execution sequence of these methods are no longer the order of page arrangement. If the JS files are mutually dependent, problems will occur.
Therefore, although we may have many other methods to avoid problems, putting JS references and inline JS Code at the bottom is obviously the most recommended.
JavaScript and CSS should be put in a separate file for reference instead of inline
This method has been adopted by developers. Inline may reduce the number of HTTP requests. Isn't it a practice we advocate? That's right. The advantage of putting it on the outside is enough for you to give up on this idea. The most important thing is that JS and CSS files externally referenced can be cached by the browser, that is, we download the page once. After that, all pages will not be requested to download these JS and CSS files, it saves more than just the number of requests. Once again, it is easy to maintain. The same JS only needs to be modified once. In addition, it is easy for us to compress and confuse Javascript. In addition, for JS outside the network, we can omit the inline JS <! --- <! [CDATA [................... ]> --> For better compatibility.
Reduce JS/CSS file size
In terms of terms, it is compression, but it is not discussed here. Gzip is a compression algorithm of the server. After receiving it, the browser decompress it and then parse it to reduce the size of transmitted data, it also causes the side effects of compression/Decompression loss. The compression discussed here is useless for browser parsing in files: spaces, line breaks, indentation comments, etc. This may increase the difficulty of solving current network bugs, but these are not suitable, compared to greater benefits, this is nothing. This compression not only reduces the size of transmitted data, but also reduces the file size, which can even speed up page parsing and greatly help page loading. Of course, it would be too miserable to perform compression manually. Yui compressor can help us complete the compression work well.
Reduce Dom operations
Javascript DOM operations are relatively slow operations, so we should note that the DOM elements to be operated are cached, rather than getelementbyid every time; try to perform all the operations before the DOM structure is appended to the page, instead of after the page is appended. Avoid modifying the layout. append a document segment containing multiple nodes instead of multiple append nodes.
Develop more flexible event handling
If there are too many events on the page bound to different elements, and these events are often executed, the page may sometimes be unresponsive. Using "event proxy" is a good method. For example, if you have 10 buttons in a DIV, and each button has event binding, then bind the event handler to the DIV, instead of 10 buttons. Through the event bubbling mechanism, you still capture the event and differentiate the event source.
Sometimes, for example, if we perform some operations on the event tree, we do not need to wait until the onload event is triggered. These operations only need to be completed after the DOM tree is built, and there is no need to wait until all the images are downloaded. In this case, the domcontentloaded event is a better choice than onload, but not all browsers support it. Onavailable of Yui, $ (document). Ready of jquery can be used.
Try to put the style in the head, regardless of the inner and referenced style.
We all know that style controls page rendering, while page Parsing is executed from top to bottom. parsing a style may affect the previously parsed content. Therefore, when a style is encountered, the page will be blocked until the style is downloaded and the display of the previous content changes is completed, inline styles can also cause re-query and display of the previously displayed content. For Some browsers, including IE, a blank page is displayed, this is not suitable for page loading and user experience.
Use a valid CSS Selector
We all know that when a page is displayed, different styles are displayed for the elements, and the inherited styles and default styles are displayed according to the style sheet. For browsers, it finds matching styles for the elements and then applies them. This search sequence selects style characters from right to left until the rule is found to be appropriate or discarded. Therefore, a small number of rules and Selection Characters are good: removing useless styles is a good optimization practice. In addition, for pages with many elements or style rules, it is also a good practice to optimize style rules. The key is to select valid separators when defining rules.
1. Avoid the combination of * and other delimiters, such as # dd *{...} Class can be inherited or applied to different elements.
2. The rules should be as clear as possible, and ID and class should be preferred.
3. Remove unnecessary restrictions. For example, the ID selector is limited by the tag name. Div # mydiv and class are limited by the Tag Name (except for the same class to distinguish different tags)
4. Avoid using descendant/child/adjacent selector. We know that the browser will apply the style from right to left. This type of selector will cause a large number of elements to be evaluated, so avoid using it, if necessary, use class to replace this type of selector. Especially those extra delimiters, such as body ul Li {...} In this case, the body is completely redundant.
5. Do not apply hover to elements other than links. In the strict IE7/IE8 mode, the hover applications outside the link are ignored. In the IE7/IE8 mode, performance problems are caused.
Do not use CSS expressions
CSS expressions are powerful and can dynamically set CSS values. They are implemented by a JS expression in style values. The expression is ignored by other browsers except ie. ie5 is added to the expression, but it is not recommended in IE8. In addition, there is also a big performance problem, that is, this expression will not only be calculated during page loading, but also when the page size changes, scrolling, or even user mouse events occur, will be recalculated. If necessary, use JS instead.
Avoid using Filters
We may use filters in IE6 at most. To support the transparency of background images, we still need to point out some problems: in this way, we cannot use background stitching to increase the number of component requests, in addition, it will block page rendering and freeze the browser during the image download process, and will increase memory consumption. But when we have to use it, please use CSS hack _ filter to make it only valid in IE6, and apply a better solution to other browsers.
Avoid @ import
When using @ import in an external CSS file, you can reference other external CSS files, but do not do this: it does not reduce HTTP requests, and only after the CSS file is parsed, this style will be discovered. in IE, this is equivalent to referencing the style file at the bottom of the page, so avoid using @ import.
Image Optimization
In terms of the size of a page, it must be an image. A picture may be several kb or even hundreds, or even a few MB smaller. It is very important to optimize the image. In addition, the images we save from software like fireworks will contain unnecessary comments that are useful for the image making software, excessive color values, useless blank images, etc. provides space for optimization. However, to make these optimizations simple, you can perform these optimizations through gimp recommended by Google or ImageMagick recommended by Yui. The following provides image optimization suggestions:
1. If the image uses 256 colors, you can try to lower it to optimize the image.
2. Select the PNG format first. Try to convert the GIF format to the PNG format and select a smaller one.
3. If the image is smaller (less than 10px * 10px) or the color is smaller (the color palette is less than 3) or the image contains an animation, use GIF.
4. Select JPG as the photo album image.
5. Do not use BMP or tiff at any time.
6. Image Compression: PNG images are compressed using the pngcrush or optipng or pngout tool. jpg files must be compressed using mongotran.
7. Ensure that favicon. ICO exists and is small enough and can be cached.
8. Avoid the existence of empty SRC images, because some browsers initiate a request to the current page.
In addition, we should pay attention
1: Image merging optimization: horizontal icon arrangement is smaller than vertical picture size, arrangement of color values similar to the merger, do not leave gaps between pictures.
2: About Image Scaling: Of course, for images that require a small size, you cannot provide a large image, and then set the width. If an image is used twice on a page, it is also appropriate to download a large one and then scale it to adapt to small demands.
3. display the size of the specified image: by displaying the width and height of the specified image, the calculation of the Image Rendering can be eliminated and the page will not be deformed when the image download fails, note that it cannot be used for image scaling and can only be added to the image itself or its parent element.
Always specify document types and character sets and ensure they are correct
The data output by the server is transmitted by bitstream containing the encoding information. Therefore, we should specify the document type and character set through http-equiv in the response header or HTML document. If the browser does not obtain such information, they buffer the information before executing JS or rendering the page until they find the character set information or take the default value, so display the specified character set. If the output data does not match the currently used character set, they have to re-parse and draw the page. If the referenced file does not match, the file will be requested again, so ensure that the correct character set is specified.
Enable gzip Compression
Note: do not enable gzip compression for images or other binary files. This usually does not work and may lead to larger files and a waste of CPU resources.
Reduce request data
In general, we try to reduce useless get or post data, and try to streamline the format as much as possible. In addition, the most operational space is the cookie. Do not store too much data in the cookie, remove unnecessary fields, and set a reasonable expiration time.
In addition, restrict the domains used by cookies to ensure that page components such as images and CSS use a domain without cookies.
Use the get Method for Ajax requests
When XMLHttpRequest is used to use post requests, it is actually executed twice: the first time the headers is sent, and the second time the post data is sent. Therefore, try to use the get method because it only sends one TCP packet (except for a large number of cookies), and the URL Length in IE is limited to 2 kb. In addition, if the POST method is used, the get method performs the same if no data is sent.
Early output buffer
When we request a page, the browser will wait-milliseconds for the server to send the following HTML page, and in this disconnected time, the browser is idle. Therefore, PHP uses flush () you can output the HTML you have prepared, and then organize the following html. In this way, the browser can parse HTML fragments and start downloading other required components. Execute flush () after the HTML head label in PHP, because the head is generally well organized and contains some CSS or JS files, in this way, you can obtain the page content and download other components in parallel.
Use CDN
The discussion about CDN seems to be beyond the scope of the frontend's consideration. As you can imagine, components are distributed to different network nodes. When a user requests, how comfortable it is to retrieve data from the nearest idle network node. But for most websites, this is almost impossible.
Optimization for mobile devices
After the gzip component is decompressed, it is kept below 25 KB because the iPhone does not cache files larger than 25 kb.
--------------------------------------------------------------------
End