What are the other ways to optimize CSS performance?

Time:2020-2-15

By TAM Hanna
Translator: front-end wit
Source: creativebloq

The more you know, the more you don’t know

Take a look at it and get used to it

This paperGitHubHttps://github.com/qq44924588… Has included more categories of previous high praise articles, as well as a lot of my documents and tutorial materials. Welcome to star and perfect, you can refer to the interview site review, hope we have something together.

In order to ensure readability, this paper adopts free translation instead of literal translation.

CSS has to go through a relatively complex pipeline, just like HTML and JavaScript, and browsers have to download files from the server, parse them, and apply them to the dom. Due to the high degree of optimization, this process is usually very fast – for small web projects that are not framework based, CSS usually accounts for only a small part of the total resource consumption.

The framework breaks the balance. Including a JavaScript GUI stack, such as the jQuery UI, you can watch CSS, JS, and HTML grow in size. Usually, developers will finally feel pressure. When they use the T3 Internet behind a powerful 8-core workstation, no one cares about speed, which changes with the emergence of delayed or CPU limited devices.

Optimizing CSS requires a multidimensional approach. Although hand written code can be simplified using various techniques, it is inefficient to check framework code manually. In these cases, simplification with automation can produce better results.

The following steps will take us into the world of CSS optimization. Not everyone can be directly applied to your project, but be sure to remember them.

01. Use abbreviation

What are the other ways to optimize CSS performance?

Use abbreviations, as shown belowmarginDeclaration, can fundamentally reduce the size of CSS files. Search on GoogleCSS ShorthandMany other shorthand forms can be found.

p { margin-top: 1px;
    margin-right: 2px;
    margin-bottom:  3px;
    margin-left: 4px; }

p { margin: 1px 2px 3px 4px; }

02. Find and delete unused CSS

What are the other ways to optimize CSS performance?

Delete unnecessary CSS, J will obviously speed up the loading of web pages. Google’s Chrome browser has this out of the box capability. Just go to view > developers > developer tools, open the sources tab in the latest version, and then open the command menu. Then, select Show coverage and highlight the unused code on the current page in the coverage analysis window to open your eyes.

Open Google browser development tool inConlseNext to more optionsCoverage, you can see the unused CSS, click the corresponding item, and highlight the unused code on the current page, which will open your eyes:

What are the other ways to optimize CSS performance?

03. Do this in a more convenient way

What are the other ways to optimize CSS performance?

In line by line analysis, navigation is not necessarily convenient. Using Google’s audits can help us analyze, use, open developer tools, and clickAuditsField, clickRun auditsThen start analyzing the results.

04. Pay attention to these problems

Keep in mind that automatic analysis of CSS always leads to errors. After replacing an uncompressed CSS file with a compressed one, thoroughly test the entire site – no one knows what errors the optimizer will cause.

05. Inline key CSS

It takes time to load external stylesheets because of delays — so you can put the most critical code bits inheadMedium. However, make sure you don’t overdo it, and remember that people who perform maintenance tasks must also read the code.

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>

06. Allow antiparallel parsing

@importAdd CSS styles to your code easily. Unfortunately, these benefits are not without cost: because@importThey can be nested, so they cannot be parsed in parallel. A more parallel approach is to use a series of<link>Tags that the browser can get immediately.

@import url("a.css");
@import url("b.css");
@import url("c.css");

<link rel="stylesheet" href="a.css">
<link rel="stylesheet" href="b.css">
<link rel="stylesheet" href="c.css">

07. Replace pictures with CSS

A few years ago, it was common for a set of translucent PNGS to create translucent effects on websites. Now, CSS filters provide an alternative to saving resources. For example, the following code snippet ensures that the picture in question is displayed as its own grayscale version.

img {
    -webkit-filter: grayscale(100%); 
    /* old safari */
    filter: grayscale(100%);
}

08. Using color shortcuts

Common sense tells us that a six digit color descriptor is the most effective way to express color. This is not the case – in some cases, shorthand descriptions or color names can be shorter.

target { background-color: #ffffff; }
target { background: #fff; }

09. Delete unnecessary zero sum units

CSS supports multiple unit and number formats. They are a thankful optimization goal – trailing and trailing zeros can be removed, as shown in the following code snippet. Also, keep in mind that zero is always zero and adding dimensions does not add value to the information contained.

padding: 0.2em;
margin: 20.0em;
avalue: 0px;
padding: .2em;
margin: 20em;
avalue: 0;

10. Eliminate too many semicolons

This optimization requires caution because it affects code changes. The specification for CSS allows you to omit the last semicolon in a property group. Since the cost savings of this optimization method are very small, we mainly focus on those programmers who are developing automatic optimization.

p {
. . .
    font-size: 1.33em
}

11. Use texture atlas

Because of the protocol overhead, loading multiple small pictures is inefficient. CSS wizard combines a series of small pictures into a large PNG file, and then decomposes it through CSS rules. Programs such as texturepacker greatly simplify the creation process.

.download {
  width:80px; 
  height:31px; 
  background-position: -160px -160px
}

.download:hover {
  width:80px; 
  height:32px; 
  background-position: -80px -160px
}

12. Omit PX

A simple way to improve performance is to use a feature of the CSS standard. The default unit for a value of 0 ispx——DeletepxYou can save two bytes per number.

h2 {padding:0px; margin:0px;}

h2 {padding:0; margin:0}

13. Avoid properties requiring performance requirements

Analysis shows that some tags are more expensive than others. The following resolutions affect performance – try not to use them if not necessary.

border-radius
box-shadow
transform
filter
:nth-child
position: fixed;

14. Delete space

Spaces – consider tabs, carriage returns, and spaces – make your code easier to read, but it’s not useful from a parser’s point of view. Remove them before publishing, and a better way is to delegate this task to a shell script or similar tool.

15. Delete note

Comments also have no effect on the compiler. Create a custom parser to remove them before publishing. This not only saves bandwidth, but also makes it harder for attackers and clones to understand the ideas behind the code at hand.

16. Use automatic compression

Yahoo’s user experience team has created an application that handles many compression tasks. It is published as a jar file, available here, and can be run using the selected JVM.

java -jar yuicompressor-x.y.z.jar
Usage: java -jar yuicompressor-x.y.z.jar
 [options] [input file]
Global Options
    -h, --help                Displays this
 information
    --type <js|css>           Specifies the
 type of the input file

17. Run it at NPM

If you want to integrate the product into node.js, visit npmjs.com/package/yuicompressor. A poorly maintained repository contains a set of wrapper files and JavaScript APIs.

var compressor = require('yuicompressor');
 compressor.compress('/path/to/
file or String of JS', {
    //Compressor Options:
    charset: 'utf8',
    type: 'js',

18. Maintain sass inspection

While the performance of CSS selectors is not as important as it was a few years ago (see resources), frameworks like sass sometimes produce very complex generations, looking at output files from time to time, and considering ways to optimize results.

19. Set cache

There is an old saying that the fastest files will never be sent over the network. Let browser cache requests do this effectively. Unfortunately, the cache header must be set on the server. Taking advantage of the two chrome tools mentioned above, they provide a quick way to analyze the results of changes.

20. Breaking cache

Designers usually don’t like caching because they are worried that browsers will cache the last stylesheet. An easy way to solve this problem is to include tags with filenames. Unfortunately, because some agents refuse to cache files with “dynamic” paths, the scheme outlined in the code accompanying this step is not applicable everywhere.

<Link rel="stylesheet" href="style.css?v=1.2.3">

21. Don’t forget the basics

Optimizing CSS is just part of the game. If your server does not use HTTP / 2 and gzip compression, you will lose a lot of time during data transmission. Fortunately, solving these two problems is usually simple. Our example shows some adjustments to the common Apache servers. If you find yourself on a different system, just refer to the server documentation.

pico /etc/httpd/conf/httpd.conf
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css



The bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time has been spent on log debugging. In this way, we recommend a good bug monitoring tool fundebug.

Original: https://www.creativeblog.com/


Communication

The articles of dry goods series are summarized as follows. I think it’s a good idea to order a star. Welcome to learn from each other.

https://github.com/qq44924588…

Because of the space limitation, today’s sharing is only here. If you want to know more about it, you can sweep the bottom two dimensional code of each article, then pay attention to our WeChat official account, and learn more information and valuable content.

What are the other ways to optimize CSS performance?