javascriptcsscss-purge

How to extract unused CSS/JS (not just purge) into a separate file?


My goal is to eliminate render-blocking CSS and JS on a website.

Google suggests to identify the used CSS/JS via coverage, and move that code from the render-blocking URL to an inline script tag in your HTML page. When the page loads, it will have what it needs to handle the page's core functionality.

For example for core CSS:

<style type="text/css"></style>

The rest of the CSS can then be loaded asynchronously via preload.

<link rel="preload" href="non-core-styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="non-core-styles.css"></noscript>

I have come across Purgecss that can remove unused css.

purgecss --css bootstrap-grid.min.css --content index.html --out dist/

But I would rather like to extract the unused CSS in order to load them async via preload as explained above to avoid any issues with the website itself.

How can this be achieved with Purgecss or any other tool, please?

Same goes with javascript. The core can be loaded like this:

<script src="app.js"></script>

While the non-critical parts can be loaded async like this:

<script src="app.js" async></script>

But is there a tool that can extract the unused JS from my site though?

Thanks


Solution

  • Take a look at https://github.com/pocketjoso/penthouse for extracting the 'critical' CSS for a page, this will then go in your <style type="text/css"></style> tag.

    I'd recommend then including all of your CSS in the CSS file via a link tag. This will mean it's the same on each page and can be cached by the browser.