Is there any way to remove CSS and JS codes not used by the application?

Asked

Viewed 4,890 times

5

I wonder if there are any transpilator analysing the classes and ids used in an HTML page and removes all classes and ids not used in CSS and Javascript.

This would be interesting to further decrease the files improving the performance of the pages.

  • 2

    Type the Tree Shaking?

  • 1

    You want something automatic for large volumes, or it can be an answer with a simpler solution that helps you do it "manually" and on a small scale?

  • I would like to know a little about the two

1 answer

7


As you said that a "small scale" solution also suits you, I’ll give you a tip using the Aba Coverage of DevTools from Chrome. Google link https://developers.google.com/web/updates/2017/04/devtools-release-notes#Coverage

In the Aba Coverage vc can evaluate what code is really in use, worth both for CSS and JS. I left the comments in the image.

inserir a descrição da imagem aqui

The detail is that for example the responsive CSS is only marked as Green when it is actually activated. This is the only drawback of this technique, because you have to navigate the page to see what is used or not. Note that as I said does not exist <h1> in HTML, then the CSS rule of <h1> will never turn Green

inserir a descrição da imagem aqui




See this other image with a larger document!

inserir a descrição da imagem aqui




As I said, it is not the perfect solution for large projects, but if it is used from the beginning and doing the audits right in short periods of time and possible to control well what is actually using and what is "garbage"...




EDIT How to open the COVERAGE TAB

inserir a descrição da imagem aqui




Extension for Chrome

In the Chrome Web Store you also find some extensions that help in this https://chrome.google.com/webstore/detail/code-coverage-calculator/ncdifkcipeniikkbckejmnbbcofdheig


Automating with Purgecss

You can use tools like Purgecss https://www.purgecss.com/ to delete CSS code that you are not using, you need to have Node installed. Basically it will read your HTML compare with CSS and drop one . css purified only with the fact you are using. The cool thing is that you can configure it to run with Ruby, or on compilers like Gulp and Grunt or in Webpack. Ai whenever compile it already purges. Here’s the project in Git https://github.com/FullHuman/purgecss

  • Which version of Crome this is available?

  • @Marconi as per the link from the version 59 have to give a F5 after opening the tab https://developers.google.com/web/updates/2017/04/devtools-release-notes#Coverage I edited the answer showing how to open this tab in Devtools

  • Regarding the activation of the property @media, can put the screen in responsive mode for multiple devices.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.