How to check unused css in website

Discover how UnusedCSS can help your website

On average, about 35% of CSS code is completely unnecessary. We meticulously find and remove this unnecessary CSS code.

FASTER WEBSITE

A faster website can lead to more sales. Less CSS code means less time to download your web page, and less time for a web browser to parse and display it.

STRONGER ENGAGEMENT

Whether your engagement metrics include products bought or number of ads viewed, a faster website can help you achieve your goals.

MAINTAINABLE CODE

We work out which rules you are actually using by looking at your HTML and Javascript. Less clutter in your code means better maintainability.

What is this

First of all, this is a beta version, we're still testing it.

This tool checks your website for unused CSS selectors. It follows internal links on your website recursively and looks on multiple pages.

How it works

  1. the tool crawls the "root" URL you provide
  2. it extracts stylesheets found in all linked CSS files and inline styles
  3. parses the page to find unused selectors
  4. parses the page to find all internal links and repeats step 3 [recursively]
  5. shows unused selectors allowing you to remove unused CSS from your stylesheets

NOTE: the stylesheets are extracted on the first page only. The tool does not re-extract the styles from your other pages.

Limits and other notes.

Currently the tool is only 200 pages deep, we're still testing it and will increase the limit shortly. Half of the work is done on our server's side [we can't do everything on the client-side because of the CORS limitations], so please don't abuse it. Results are cached for 24 hours, please be patient. If you see a flickering iframe at the bottom of the page it's OK, your pages are being [somewhat] loaded into it. We'll remove it after testing is done. Frankly, we are just testing the concept and if there's enough demand we'll keep developing the tool further and even post the sources on Github. Send your bug reports to @jitbit on Twitter.

Known issues

The tool might show pseudo-classes as unused, like :hover or :focus. Obviously because it was unable to find any "hovered" elements on the page.

Actualy, before removing any "unused" style form your css-file, double-check that it's really not being used :]

By Cody Arsenault

Updated on March 4, 2019

It's no secret that leaner websites run faster than bloated ones. Don't let unnecessary CSS weigh down your web projects; use the tools and techniques described below to help you remove unused CSS and improve your website's overall performance.

What is unused CSS?

No matter how experienced you are as a developer, there is a good chance that your website contains CSS that have no impact on current page elements. For example, frameworks like Bootstrap come with dozens of CSS styles that you probably don't need. If you added a feature during development and removed it later on, there could still be rules associated with that feature lingering in your style sheets. Unused CSS just adds dead weight to your applications and contributes to the growth of web page size, so you want to make sure that you have as little excess code as possible.

Why should you remove unused CSS?

Since CSS defines how content in an HTML document gets displayed, the user's browser must download and parse all external CSS files before it can start rendering content. Consequently, the more CSS a web page contains, the longer users must wait to see anything on their screens. Inlining small CSS within your HTML file and minifying your external style sheets can help optimize content rendering, but cutting out useless CSS is a far more effective strategy for improving overall performance. Combining all of these methods ensures that users see content as quickly as their internet connection will allow. Aside from slowing down your website's overall performance, excess CSS can cause headaches for developers. Clean and orderly style sheets are easier to maintain than disorderly ones. Do your users and yourself a favor by ditching unused CSS.

How to remove unused CSS manually

If you're using Chrome, the DevTools tab has a handy tool that allows you to see what code is being executed on a page on what isn't. To access this tool, follow the steps below:

  1. Open Chrome DevTools
  2. Open the command menu with: cmd + shift + p
  3. Type in "Coverage" and click on the "Show Coverage" option
  4. Select a CSS file from the Coverage tab which will open the file up in the Sources tab

Any CSS that is next to a solid green line means that the code was executed. Solid red means it did not execute. A line of code that is both red and green, means that only some code on that line executed.

Just because a style isn't used on one page doesn't mean that it's not used elsewhere, so you should audit several pages on your site and keep track of which rules keep appearing on the unused list. You can do this by copying and saving the results of each audit into a Google Sheets document. The ones that appear the most can probably be safely removed.

Most developers have better things to do than delete unused CSS rules one by one. That's why there are a variety of tools designed to automate the process. Here is an overview of the most popular tools designed to help web developers remove unused CSS from their web projects:

1. UnusedCSS

The simple name is indicative of this program's user-friendliness. Just plug your website's URL into UnusedCSS and let it do all of the work. In addition to identifying and removing unused CSS rules, it tells you how much memory you've saved. You can try UnusedCSS out for free, but you must pay for a monthly membership to download your cleaned up CSS files. Premium members can schedule automatic CSS optimizations and have access to other features; however, it should be noted that UnusedCSS only works with live websites, so it's not useful in the testing phase.

2. PurifyCSS

PurifyCSS is a free tool that removes unused CSS from your HTML, PHP, JavaScript and CSS files before you go live. On the downside, you must manually specify which files to scan one by one, which makes the process somewhat tedious. Rather than modifying your original files, PurifyCSS outputs a new file with the optimized CSS. Since PurifyCSS doesn't work with live websites, you'll need to use it in a development setting. You may want to use PurifyCSS during development and upgrade to UnusedCSS later on.

3. PurgeCSS

PurgeCSS was inspired by PurifyCSS, so it looks very similar, but it's a bit more streamlined and intuitive to use. It works by comparing your content to your CSS files and removing selectors that don't have a match. The only major downside is that you must manually whitelist CSS not in the specified paths, which can be a headache if your website uses certain plugins such as HTML Forms.

4. UnCSS

UnCSS is more accurate than PurgeCSS since it looks at actual web pages rather than the individual files, but its slower and requires more manual set up. UnCSS is most helpful when used with other tools. For example, you can combine UnCSS with Grunt and Node.js to automate unused CSS removal.

A word of warning about removing unused CSS

The tools discussed in this tutorial are not perfect. There are a few different methods for identifying rouge CSS selectors; however, matching selectors to elements in the DOM can be tricky if you have elements that depend on APIs and third party scripts. If you want to try removing unused CSS manually, then you need to be extra careful so that you don't accidentally cripple your application by deleting something important. That said, you should know your website better than anyone else, and the DevTools auditing feature can provide some valuable insight to help you create tighter CSS from the start.

How to automate unused CSS removal with UnCSS

Now, let's see how we can use one of the tools listed above to trim down your style sheets. This tutorial, thanks to Dean Hume, will explain how to set up Node.js, Grunt, UnCSS and another plugin called CSSmin on a Windows machine to automatically remove unused CSS and minify the results.

1. Install Node.js

Download the latest distribution from the Node.js website and follow the installation instructions.

2. Install Grunt

Open Node.js and enter the following into the command prompt:

npm install -g grunt-cli

Grunt should download and install automatically.

3. Open your project folder

Using the Node.js command prompt, navigate to the folder containing the files you want UnCSS to scan. You can do this by entering the file path. For example:

cd C:TestProject

4. Install UnCSS and CSSMin

Enter the following into the Node.js command prompt:

npm install grunt-uncss grunt-contrib-cssmin --save-dev

UnCSS and the CSSMin package will be installed in the specified project folder.

5. Create a gruntfile.js file

Create a JavaScript file called gruntfile.js in your project's root directory. The gruntfile.js acts as a configuration file for plugins like UnCSS. Enter this code into the Node.js command prompt:

module.exports = function [grunt] {
    grunt.initConfig[{
        uncss: {
            dist: {
                files: [
                    { src: 'index.html', dest: 'cleancss/tidy.css' }
                ]
            }
        },
        cssmin: {
            dist: {
                files: [
                    { src: 'cleancss/tidy.css', dest: 'cleancss/tidy.css' }
                ]
            }
        }
    }];

    // Load the plugins
    grunt.loadNpmTasks['grunt-uncss'];
    grunt.loadNpmTasks['grunt-contrib-cssmin'];

    // Default tasks
    grunt.registerTask['default', ['uncss', 'cssmin']];
};

The above instructions tell UnCSS to scan your index.html file for unused CSS and create a trimmed down CSS file inside a folder named cleancss. The CSSmin plugin will then minify the new CSS file, which will be called tidy.css by default. The final few lines are especially important since they load and register both plugins.

6. Run Grunt

Finally, you must navigate back to your source file folder and run Grunt like so:

cd C:TestProject>grunt

That should set UnCSS and CSSmin into action. If you did everything correctly, you'll have a clean and minified CSS file waiting for you in the specified folder. Some developers have claimed that this method reduced the size of their CSS files by more than 95 percent! That's a lot of savings for minimal effort. You only have to perform the setup process once. In the future, you can just run Grunt to automatically strip your project of unused CSS.

Summary

In addition to unused CSS, your website probably has some HTML and JavaScript that it could do without. Before you start concatenating, minifying, and compressing your files, make sure they're not bloated with unnecessary code and remove unused CSS.

How do I remove unwanted CSS from my website?

4 Ways to Remove Unused CSS. How to remove unused CSS to reduce your app's bundle size and maintain a clear and simple code. ... .
PurgeCss. Introduction. ... .
PurifyCSS. PurifyCSS Online - Remove unused CSS. ... .
uncss. UnCSS Online! ... .
Coverage Tab in Chrome DevTools [Manually] This Coverage tab helps us find unused Js and CSS code..

How do I find unused CSS and JavaScript files in my website?

You can find it via the following steps:.
Open Chrome DevTools. Control + Shift + I. ... .
Open the Command Menu. Control + Shif t +P. ... .
Type + click the following: "Show Coverage".
Click the reload button to reload the page and to see which code is loaded..
Then double click on the JS or CSS file that you want to unminify..

How do I clear unused CSS?

If you want to remove unused CSS entirely, you can use a tool such as PurifyCSS to find out how much CSS file size can be reduced. Once you get the CSS code you should eliminate, you have to remove it manually from the page.

How can I see all CSS?

On Chrome's Developer Tools tab [CTRL + SHIFT + I], go to Resources [you may have to enable Resource tracking on that page], and click on the sub-tab Stylesheets. That will show all css files loaded by that page.

Bài mới nhất

Chủ Đề