I have a large legacy web project in NetBeans. The majority of the CSS files are included in the header. Some CSS are required on all (or almost all) pages and some are only on a subset of pages.
I want to reorganize at least the pages with high traffic to make sure that they don't include unused CSS. For this I will have to create multiple small CSS files to be included there (to leave only the minimum number of includes in the header). But I am afraid that if I have multiple external CSS includes it will lead to more http requests for that page, so I am not sure what is the best way to go about this. I want to improve page performance, but I do not want to reduce unused CSS and end up having too many http requests on those pages.
What would be a good solution/compromise for this situation?
Thank you!
Its tough to do this with legacy code because you then would have to pour over it and see what is actually being used in page, not too sure of the best route to take there but for new projects there are a few ways to organize your css. First lets discuss pure css:
There isn't much of a way to get around multiple requests except for some .htaccess trickery (look at the answer about .htaccess trick), so aside from that you need to break up your css in a sensible way, here is how I handle this.
Everypage gets these:
normalize.css stylesheet
base.css stylesheet (contains styles for default elements like form elements, headers, paragraphs and so on
Then we get more specific, I try to keep my code as modular as possible so I try to group UI compoments together like tabs and sliders and what not so then I would have
and finally individual sheets for sections of the site, if i have admin section there is
admin.css
for those things that are too specific for any above fileI may also have account.css or app.css for forward facing code
Now if you can use something like Less or Sass you can really optimize your code.
Because you have the power to pre-compile and you can use imports you can create less files for sections of your site/app and just import css components, an example would be like this:
admin.less
app.less
And that is all these master files contain. This way when you need to make changes or add new code or a new feature you can create a new file and then just import it. You can also create as many master files as you want and only pull in exactly what is needed on each page.
This gives you great control and makes your css easy to maintain and really scalable, while also enhancing performance by allowing you to only include what is needed.
Hope this is helpful!!