CSS optimization Summary-network performance and syntax performance suggestions

Source: Internet
Author: User
Tags border color

The most common problems in front-end interviews are page optimization and caching (which seems to be page optimization too). After being asked several times, you may not be able to use it, however, it is difficult to tell me what I know. Page optimization is obviously not a sentence or two. In the past two days, I have summarized CSS-related optimization knowledge, written a blog, and hope you can give me more advice.

CSS optimization mainly starts from two aspects.

  • Network Performance: writes CSS to the smallest number of bytes to accelerate the download speed, which naturally makes page rendering faster.
  • Syntax performance: some effects can be achieved in the same way, but not all methods have the same effect. We have seen a lot of knowledge about JavaScript syntax optimization. In fact, CSS also has some
CSS Compression

CSS compression is not a high-end posture, but it is very useful. Its principle is very simple. It is to delete blank characters that are useless in our CSS to reduce the number of characters.

We have such a CSS script.

.test{    background-color:#ffffff;    background-image:url(a.jpg);}

This will happen after compression

.test{ background-color:#fff;  background-image:url(a.jpg)}

Of course, some advanced compression tools will also help us optimize some syntaxes and provide many options to make our compression more controllable. Previously, the company did not adopt CSS compression, so I have no practical experience, YUI Compressor is commonly used to write your own things. It is very convenient to have many online versions.

YUI Compressor

CSS Compressor

CSS drive

Clean CSS

Do you have any good resources to recommend?

Gzip Compression

Gzip is a popular File compression algorithm. It is widely used nowadays, especially on Linux platforms. This is not only for CSS, but when Gzip is applied to a plain text file, the effect is very obvious, which can reduce the file size by more than 70% (depending on the content of the file ). For more information about gzip, see Wikipedia.

Without gzip compression, the Web server directly sends html pages, CSS scripts, and js scripts to the browser. The Web server that supports gzip will compress the files and send them to the browser, the browser (gzip supported) decompress and decode locally and display the original file. In this way, the number of file bytes transmitted is reduced, and the network performance can be optimized. Gzip compression requires server support, so we need to configure it on the server side.

Enable Gzip compression (HTTP compression) on IIS)

How to enable gzip compression in apache

Nginx Gzip compression Configuration

Of course, in addition to gzip compression, cache is also worth attention, which has little to do with CSS optimization. Let's talk about web optimization.

CSS combination

In addition to compression, we can also reduce CSS bytes by writing less CSS attributes. Take the most common example.

.test{ background-color: #000; background-image: url(image.jpg); background-position: left top; background-repeat: no-repeat;}

We can rewrite the above CSS to achieve the same effect.

.test{  background: #000 url(image.jpg) top left no-repeat;} 

There are many similar attributes in CSS that can be written together.

Font

{font-style: oblique; font-weight: bold; font-size: 16px; font-family: Helvetica, Arial, Sans-Serif;}{font: oblique bold 16px Helvetica, Arial, Sans-Serif;} 

Margin/padding

{margin-top: 5px; margin-right: 10px; margin-bottom: 20px; margin-left: 15px;}{margin: 5px 10px 20px 15px;} 
{padding-top: 5px; padding-right: 10px; padding-bottom: 5px; padding-left: 10px;}{padding: 5px 10px}{padding-top: 5px; padding-right: 5px; padding-bottom: 5px; padding-left: 5px;}{padding:5px;}

Background

{background-color: #000; background-image: url(image.jpg); background-position: left top; background-repeat: no-repeat;}{background: #000 url(image.jpg) top left no-repeat;} 

Border

{border-width: 2px; border-style: solid; border-color: #000;}{border: 2px solid #000;}
{border-top: 2px; border-right: 5px; border-left: 10px; border-bottom: 3px;}{border: 2px 5px 10px 3px;}

In addition, many attributes added by CSS3, such as transform and animation, can be written together and not listed one by one. Pay attention to this when using CSS3.

Use inheritance

The Inheritance Mechanism of CSS can also help us reduce the number of bytes to a certain extent. We know that CSS has many attributes that can be inherited, that is, the parent container has set the silent write attribute, the sub-container uses these attributes by default. Therefore, if you want the full text font size to be 14px, you do not need to set the size for each container. You only need to set the size on the body. By applying this technique, it is possible to mention the CSS attributes. The parent container can help us save CSS bytes. By the way, which attributes can be inherited?

  • All elements can inherit: visibility and cursor
  • Inline and block elements can be inherited: letter-spacing, word-spacing, white-space, line-height, color, font, font-family, font-size, font-style, font-variant, font-weight, text-decoration, text-transform, and direction
  • Block elements can be inherited: text-indent and text-align
  • List elements can be inherited: list-style, list-style-type, list-style-position, list-style-image
  • Table element inheritance: border-collapse
  • Not inherited: display, margin, border, padding, background, height, min-height, max-height, width, min-width, max-width, overflow, position, left, right, top, bottom, z-index, float, clear, table-layout, vertical-align, page-break-after, page-bread-before, and unicode-bidi

Attributes that can and cannot be inherited in css

Extract and split CSS, do not load all CSS

CSS extraction refers to placing some common CSS in a file, rather than writing various pages. After a download, other pages can be used with cache, reduce unnecessary repeated downloads.

In many cases, the general CSS of the page is written to a file, so that the cache can be used once loaded. However, this method is not suitable for all scenarios, previously, I wrote CSS to write all the CSS used by some front-end plug-ins to one page, but sometimes the page only uses one Dialog and some pages only use one TreeView, but it downloads the CSS of more than 10 ins to the page, which is the problem. Although writing a file with CSS can reduce http requests, however, we should not do this just now. We can do this for all the pages we use, so we can think about it well when we pull and split.

CSS sprites

This is not actually CSS optimization. It should be said that CSS is used in web optimization. By the way, if you are interested, you can see how to use CSS sprites to reduce HTTP requests.

 

There are so many things you can think of in terms of network performance for the time being. I hope you can help correct and supplement them and look at some syntactic performance optimizations.

CSS is placed in the head to reduce repaint and reflow

I believe that all web users know this suggestion. But why is CSS placed on the top of the page conducive to webpage optimization? This is probably the case in browser rendering pages. When the browser downloads the html-generated DOM tree from the top to the bottom, the browser generates the render tree based on the browser's default and existing CSS to render the page, when a new CSS is downloaded and the existing CSS is used to generate a render tree, the rendering work is in vain. If we put all the CSS on the top of the page, in this way, there is no re-rendering process. If you are interested in the working principle of the browser, you can refer to Shen Wen

Working principles of browsers: New Web browsers reveal behind the scenes, and I believe I will have a deep understanding of the working principles of browsers.

Similarly, we know that we should also try to reduce repaint and reflow in the script. What will lead to these two situations?

Reflow: When the DOM element is hidden/displayed, the size changes, and the position changes, the browser will re-render the page. Previously, the rendering work was in vain.

Repaint: When the background color and border color of an element do not cause reflow changes, the browser will re-render the element. It seems acceptable, but if we define it at the beginning, it would be better to prevent the browser from repeating the work.

No CSS expressions

No matter how the CSS is generated, we finally put it on the page is static normal text, no variables, the calculation of the magic horse, CSS expression is a dynamic setting of CSS attributes of the East, supported by the IE5-IE8, let's look at a common example.

body {  background-color: expression((new Date()).getHours()%2?"#B8D4FF":"#F08A00");}

In this way, CSS is provided with functions similar to JavaScript. CSS expressions are very powerful. You can even use CSS expressions to implement the min-width attribute, change the color across rows, simulate: hover,: before ,: after and other pseudo classes seem to be able to solve many issues such as browser compatibility in IE, But the side effects are beyond our imagination. This CSS rule is not only run once, to ensure the effectiveness, CSS expressions Frequently evaluate the value. When the window size is changed, scrolling pages or even moving the mouse will trigger the expression to evaluate the value, so frequent evaluate so that the browser performance is seriously affected. According to the "high-performance website construction suggestions", the number of tests is far more than we think. If you are interested, you can go in and try to avoid or even avoid using CSS expressions.

CSS reset or attribute setting

During website construction, we often use some CSS resets to achieve cross-browser unification. However, many times our CSS reset is too bloated and there are two main problems.

  1. It is unnecessary to set one side for the default attributes of elements in many browsers, for example, the padding and margin of div are 0.
  2. Some very uncommon element settings are also written into CSS reset, such as ruby.

A few days ago, I wrote an article about the default attribute values and interactions of common CSS reset-related blog tags-I am a bit familiar with CSS reset. I hope you can criticize and correct them.

Avoid wildcard or implicit wildcard

* In CSS represents a wildcard. Although it is easy to use, improper use is also a devil, such

body * {padding:0;margin:0;} 

We thought this was to set some attributes for the child node of the body, but because of the CSS inheritance feature, all elements on the page will accept this rule, the performance of complex pages is still greatly affected. This does not mean that wildcards cannot be used, but the scope of use should be noted. We believe this rule is well known, but some implicit wildcards also need our attention, such

:visible{  padding:0;}

This is almost the same as the wildcard character. You must pay attention to the range restriction when using it.

Avoid hierarchical or overly restrictive CSS

It is estimated that all web developers have read Writing efficient css on the mdn or their translation versions. This article summarizes some comments on Writing CSS selector, one premise of understanding the suggestions in this article is to know that CSS is parsed from right to left, rather than from left to right. The reason for this is that it is efficient, you can search for related knowledge online.

Copy the article

Do not use tags or classes to restrict ID rules.

This should be a common sense, but many people will misuse it and write a selector such as # test.info or div # test. This can only be said to be superfluous. The id can be unique and the fastest way to locate an element.

Do not use label names to restrict class rules

This estimation is more misused, such as div.info. In fact, we can directly write it. info, the reason for parsing from right to left can be understood why it is inefficient. If you can't achieve the goal by using class directly, it should be a problem in the class design, and CSS needs to be reconstructed.

Use the most specific category as much as possible, avoid descendant selector, and rules that belong to the label category AlwaysDo not include a child Selector

These three rules are figured out, because the link is parsed from left to right. In the CSS selector, the descendant selector does not accelerate CSS search,The descendant selector is the most expensive selector in CSS.It is extremely expensive-Especially when the selector is in a label or a common categoryThe author's suggestion is:Exercise caution when using a sub-selector.. The overhead is evident.

To solve this problem, we can use a single or as few classes as possible.

Last

We usually use and understand the methods for optimizing CSS to achieve page optimization. I hope you will give your comments and comments.

Via: dolphloud
Original article address: Common CSS optimization Summary-network performance and syntax performance suggestions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.