CSS Optimization - 21 Ways to Speed Up Your Website

print · Время на чтение: 8мин · - · Опубликовано · Обновлено

playListen to this article

How to optimize CSS for performance.

css must go through a relatively complex pipeline, just like HTML and JavaScript. The browser must download the files from the server and then proceed to parse them and apply them to the DOM. Due to the extreme levels of optimization, this process is usually quite fast - for small web projects that are not based on frameworks, CSS usually makes up only a small part of the total resource consumption.

Frames break this balance. Include a JavaScript GUI stack like jQuery UI and watch your CSS, JS, and HTML grow exponentially. Often developers do not feel bad - when they sit at a powerful eight-core workstation with T3 Internet, no one cares about speed. This is changing as latencies or devices with CPU limitations come into play.

CSS optimization requires a multidimensional approach. While handwritten code can be reduced using various methods, iterating over the framework code by hand is inefficient. In these cases, using the automatic minimizer gives better results.

The following steps will help you optimize your CSS. Not all of them may be directly applicable to your project, keep that in mind.

The content of the article:

Use Shortcut CSS Suggestions

CSS optimization for fast page loading.

The fastest CSS sentence is the one that is never parsed. Using shorthand suggestions like the field declaration shown below will drastically reduce the size of your CSS files. Lots of additional shorthands can be found by googling "CSS Shorthand".

Here is an example:

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

Remove unused CSS code

Eliminating unnecessary parts of your markup obviously results in a huge increase in speed. The Google Chrome browser has this feature out of the box.

Just go to View > Developer > Developer Tools, open the Sources tab in the latest version, and open the command menu. After that, select "Show Coverage" and admire the coverage analysis window highlighting unused code on the current web page.

Work with CSS in a more convenient way

Navigation through line-by-line analysis is not necessarily convenient. Chrome Web Performance Audit returns similar information - just open it from the toolbar, choose View > Developer > Developer Tools > Audit, and run it. When this is done, a list of problematic items will appear.

Always be aware of issues related to your styles

Keep in mind that automated CSS parsing can always lead to errors. Do a thorough test of the entire website after replacing the CSS files with minified ones - you never know what mistakes the optimizer made. And going forward, a decent web host can help you iron out the wrinkles on your site.

Inline Critical CSS

Loading external style sheets takes time due to latency - does anyone remember the "flash of unstyled content"? This way, the most important pieces of code can be placed in the header tag.

However, try not to overdo it. Keep in mind that the code also needs to be read by people doing maintenance tasks.

Here is an example:

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

Anti-Parallel Analysis

@import @import adds structure to your CSS code. Unfortunately, the benefits are not free: since imports can be nested, they cannot be parsed in parallel. The more parallel way uses a series of tags that the browser can get at once.

Example:

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

Replace your images with CSS

A few years ago, a set of translucent PNG files to create translucent effects on websites was commonplace. Currently, CSS filters are a resource-saving alternative. For example, the snippet accompanying this step ensures that the image in question is displayed as a grayscale version of itself.

Example:

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

Use color combinations

Common sense dictates that six-digit color descriptors are the most efficient way to express colors. This is not the case - in some cases, abbreviated descriptions or color names may be shorter.

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

Remove unnecessary zeros and ones

CSS supports a wide range of units and number formats. They are a welcome target for optimization - both trailing and trailing zeros can be removed, as shown in the snippet below. Also, keep in mind that zero is always zero, and that adding a dimension does not increase the value of the information contained.

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

Remove extra semicolons

This optimization is somewhat critical as it affects code changes. The CSS specification allows you to omit the last semicolon in a property group. Since the savings achieved by this optimization method are minimal, we mention it mainly for those who work with the automatic optimizer.

p { . . . font-size: 1.33em

Use texture sprites

Loading multiple small sprites is inefficient due to protocol overhead. CSS sprites combine a series of small images into one large PNG file, which is then broken apart using CSS rules. Programs such as texturepacker , greatly simplifies the creation process.

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

Delete unwanted pixel

One nifty way to improve performance is a feature of the CSS standard. Unitless numeric values are assumed to be pixels - removing pixels saves two bytes for each number.

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

Avoid demanding proportions

The analysis showed that some tags cost more than others. The list that accompanies this step is considered especially demanding on performance - avoid it when given the opportunity to do so.

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

Remove unnecessary spaces

Spaces - think tabs, carriage returns, and spaces - make code easier to read, but don't do much from a parser's point of view. Eliminate them before shipping. Better yet, delegate this work to a shell script or similar device.

Remove unwanted comments

Comments are also useless to the compiler. Create your own parser to remove them before delivery. This not only saves bandwidth, but also makes it harder for attackers and cloners to figure out what's behind the code.

Use automatic compression

Yahoo's UI team has created an application that does a lot of compression work. It comes as a JAR file and can be run with the JVM of your choice.

java -jar yuicompressor-xyzjar Usage: java -jar yuicompressor-xyzjar [options] [input file] Global Options -h, --help Displays this information --type Specifies the type of the input file

Run from NPM

If you prefer to integrate the product in Node.JS, please visit npmjs.com/package/yuicompressor . The poorly maintained repository contains a set of wrapper files and a JavaScript API.

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

Keep Sass and others under control

While CSS selector performance isn't as critical as it was a few years ago (see resource), frameworks like Sass sometimes produce extremely complex code. Review the output files from time to time and think about how to optimize the results. Got results to share with the team? Store files in public cloud storage.

Set up caching

The old saying goes that the fastest file is the one that never goes over the wire. Querying the browser's cache achieves this efficiently. Unfortunately, setting caching headers must be done on the server. Make good use of the two tools shown in the screenshots, they provide a quick way to analyze the results of your changes.

clear cache

Designers often dislike caching for fear of problems with upcoming changes. A neat way to solve this problem involves including tags with the file name. Unfortunately, the scheme described in the code that accompanies this step does not work everywhere, as some proxies refuse to cache files with "dynamic" paths.


Don't Forget the Basics

CSS optimization is only part of the optimization effort. If your server does not use HTTP/2 and gzip compression, a lot of time is wasted when transferring data. Fortunately, solving these two problems is quite simple. My example shows several settings for a widely used Apache server using an .htaccess file. If you find yourself on a different system, just refer to the server's documentation.

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

I will be very glad if this article is useful for you. Well, I will continue to add new relevant materials on this topic.

Reading this article:

Thanks for reading: SEO HELPER | NICOLA.TOP

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 329

No votes so far! Be the first to rate this post.

Читайте также:

1 Response

  1. Илья says:

    I have been following your project for a long time. I look at the recovery, it's very nice to see changes for the better. I like your design and layout. It can be seen that you are working on quality. Thank you for your efforts.

Добавить комментарий

Your email address will not be published. Обязательные поля помечены *

20 − 3 =