I am trying to optimize a site performance by consolidating and compressing the CSS and JS files. My question is more about the (concrete) steps on how to achieve this, given a real situation I was facing (should be typical among other developers too, though).
My page references several CSS and JS files like the following:
<!-- It's easier to work on smaller files during development. Hence, the multiple CSS and JS files. --> <link type="text/css" rel="stylesheet" href="/css/main.css" /> <link type="text/css" rel="stylesheet" href="/css/secondary-1.css" /> <link type="text/css" rel="stylesheet" href="/css/secondary-2.css" /> <script type="text/javascript" src="/scripts/js/main.js"></script> <script type="text/javascript" src="/scripts/js/adapter/adapter.js"></script> <script type="text/javascript" src="/scripts/js/adapter/title-adapter.js"></script>
For the production release, I'd like to combine the 3 CSS files into one and minify it using e.g. YUI Compressor. But then, I'd need to update all pages that needs these 3 files to reference to the newly-minified CSS. This seems error-prone (e.g. you're removing and adding some lines in many files). Any other less-risky approach? The same issue for the JS files.
To combine external CSS files, you can simply copy / paste all of your CSS code into one main file. Therefore all of the content from within the other CSS files will now reside within the main file allowing the browser to only make one request for a CSS file instead of multiple.
To minify CSS, try CSSNano and csso. To minify JavaScript, try UglifyJS. The Closure Compiler is also very effective. You can create a build process that uses these tools to minify and rename the development files and save them to a production directory.
With HTTP/2, there is generally no need to combine CSS/JS files as the multiplexing feature eliminates the need for concurrent connections (unlike HTTP/1.1). Don't combine your CSS/JS files when you're on HTTP/2 or if your page has many scripts and stylesheets.
Check out minify - it allows you combine multiple js, css files into one just by stacking them into a url, e.g.
<script src="/scripts/js/main.js,/scripts/js/adapter/adapter.js"></script>
We've used it for years and it does a great job and does it on the fly (no need to edit files).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With