Quick chat I had with a friend…
Why shouldn’t I combine CSS styles and JS scripts?
To combine/merge or not. It’s an endless debate over which is better.
Merging CSS/JS looks great on performance test sites like Pingdom and GTmetrix but is it really the best performance for your site?
STOP Merging CSS/JS!
Reason #1 – it slows down your site load!
For me, merging CSS is a superficial improvement that makes your test scores look better since you have fewer requests. These page speed tests were only intended to be used as guidelines. Many of them (if not all) were designed before the new HTTP/2 protocol.
[Brief] history of evolution from HTTP to HTTP/2 protocol
- Old HTTP protocol could only load a few requests at a time, queuing the other requests (imagine 1 cashier with many customers in line). So in those days, it was better to have fewer HTTP requests. Tactics like “CSS sprites” and combining CSS/JS was standard practice. With only one cashier, having one giant order was faster than several small orders, each with their own transactional overhead in DNS request times.
- HTTP/2 protocol came out allowing parallel requests (imagine multiple cashiers instead of one). With multiple cashiers, requests were served quicker as separate smaller requests rather than combined. HTTP/2 gave such massive performance increases, you would expect almost immediate adoption. Unfortunately, it required HTTPS (TLS/SSL certificates) which weren’t yet standardized (also cost money/skills to implement).
- As expected, low-budget webhosting clients weren’t willing to pay for SSL or deal with technical hassles of setup/renewal for them. They also weren’t necessarily if you didn’t have a store. (At the time, no 1-click solution existed for installing TLS/SSL certificates; you had to copy-paste long bits of encrypted text and wonder if you did it right.)
- But then the industry changed…Google started requiring all websites to have HTTPS or risk being penalized on their search engine rankings. The only one thing left in the way was affordable TLS/SSL certificates. Luckily for everyone, Let’s Encrypt came out with free TLS/SSL certificates—HOORAY! Webhosts started offering 1-click solutions overnight and HTTPS (alongside with HTTP/2) became the standard.
- While the webhosting and web-browser industry made HTTP/2 and HTTPS standard; outdated page speed tests (and many speed-up guides) are still recommended practices like decreasing the number of requests. We are still living in that conflicted aftermath today. For the record: I’m all for decreasing code and even requests; I just don’t see the point of wasting precious server resources to combine code into one lump file that takes longer to process.
People think that because their server sent out fewer requests, it means their server did less work…but that is false thinking. Your server sends out the same amount of code no matter what. If anything, your server may work harder because you merged. Merging CSS also has a few annoying issues…instead of letting your page render immediately, it now has to wait for your entire CSS to load.
Imagine eating at a restaurant with 20 friends. Do you want the food to come out as soon as it’s ready? Or only when everyone’s order is cooked?
For me…most CSS should be loaded as fast as possible and most JS should be as delayed as possible (UNLESS, there is critical JS like being used for slider above the fold).
As for merging JS (scripts)….I think it’s great if your merging mechanism can also defer and throw them to the footer (that’s the only reason why I would merge them). But in general…and especially with well-coded sites, you don’t want it.
Reason #2 – it breaks your site
You’ll end up spending a lot of time troubleshooting sites with broken CSS/JS merges. I see “cache plugin broke my site” on WordPress Facebook groups about 2 dozen times every week.
And even if things do look alright, the site might not be perfect and or might not always get performance benefits. Your contact form might break, or some scroll function, or some ajax function. There’s a myriad of possible conflicts that can happen when you merge JS.
Reason #3 – it adds unnecessary page load
This is one of the funniest aspects of CSS/JS merge. Many people think doing it will decrease their page requests and page load but it often does the exact opposite. Merging CSS/JS combines all your stylesheets into one file and all your javascript into one file. This is a huge problem if you have a busy site with many different kinds of pages.
For example:
- Plain pages will load your pagebuilder.
- Pages that aren’t related to your store or products will load WooCommerce.
- Pages that don’t have any forms loaded will load your forms anyway.
And so forth. Imagine if you had 30-40 plugins, well guess what…now your site loads all the CSS/JS on every single page. How wasteful!
Ok fine…there are some “intelligent” CSS/JS merges that allow separate CSS/JS for every page but now this is overkill. Your server spends more time merging CSS/JS than actually serving pages to users. Feel free to experiment on your own but my general rule is not to merge JS.
Reason #4 – it delays cache prebuild
Last but not least, you don’t want to merge CSS/JS with your cache plugin because it delays the cache prebuild. Imagine a huge site like 1,000 pages. You don’t want cache plugin to rebuild html/CSS/JS for all 1k pages when you update one post. It’s better….let autoptimize or async javascript do the merging. And then your cache plugin only has to build html cache.
There’s a million tactics and it’s kind of an art in itself. Depends on what kind of site, what kind of traffic, and how often you update content.
PS: those test sites are a little bit dated. Giving suggestions that would have worked better for older webhosting technology.
But (rebuttals)…
“Doesn’t combining CSS/JS reduce the code?”
Yes, it’s true! Merging your CSS/JS often reduces code, stripping out empty spaces and unnecessary code. So it would seem like your site would load faster since there’s less code overall to load. Only problem is, that’s not how pages render.
You see, pages render as soon as an entire asset loads.
- Let’s compare uncombined CSS (split1.css + split2.css + split3.css = 60kb total) vs combined CSS (combined.css = 50kb).
It’s reasonable to think the combined css would load faster because it’s smaller, but that doesn’t always happen. There’s a good chance your site can start rendering the page with only split1.css (with split2.css & split3.css being used to render lower parts of the page). If that’s the case, you’re better off leaving the files uncombined so the page renders earlier for users. The idea here is to start rendering soon rather than finish rendering sooner. (It’s basically the concept behind “Critical CSS“.)
“But the combined CSS doesn’t have to load if it’s cached!”
That’s a great point, too. If you combine the CSS/JS and then cached it to the user’s browser locally, they wouldn’t have to download it! The only problem is…most visits to your site are going to be 1st-time visits. Even if it was just one person…they could be visiting from their desktop, their laptop, their mobile phone. Maybe a different browser, or maybe their cache cleared. Whatever reason it is, the majority of your traffic will be first-time visits.
Here’s another thing…you can cache uncombined CSS/JS files, too! Put long expiry times on them and it’s pretty much the same thing.
“What about Critical CSS?”
If your site is bloated to the point where you actually have critical CSS vs non-critical CSS, you have a different problem. Clean up your code. If your total CSS is only 40-50kb, that’s fine. Leave it un-merged.
“Are you sure about NOT merging JS?”
The topic of merging JS is a whole can of worms in itself. Let’s start with the pros and cons. Right off the bat…merging JS is always a darn risk because something breaks in your site. Second, we’re now in the age of HTTP2 where loading multiple assets in parallel beats loading one combined asset. Those 2 reasons alone are good enough to avoid it. It’s a safer option with great performance and far less issues to fix.
So what’s the best way to manage JS and when should you merge JS?
I think most JS are not critical to initial page rendering. JS usually has to do more with the page’s function than its design. Note the operative word ‘usually’. Some JS does have to do with the design…such as image sliders, tab content, expandable/collapsible divs, pop-ups, etc.
Ideally, all JS (except for design-related JS placed above-the-fold) is deferred to the end of the page load queue and doesn’t load until the rest of your design loads first. Even better is if you can prevent certain JS from not loading at all unless the user scrolls to it or interacts with it (lazyload/onload-event)…this would be great for things like super bloated Googlemaps iframe laying at the bottom of the site.
Some of the merging mechanisms out there will do all that…combine your JS and defer it. And then you could manually exclude certain critical JS files from being merged and deferred. And also put some on lazyload if you wanted.
“But my site has faster speed scores with CSS/JS combined!”
This is a great reason many people use to justify combining CSS/JS. And in some cases, it’s true—combining CSS/JS might get you a faster FINISHING load time. But here’s the thing…what we want is faster STARTING load time.
Remember that whole trend about optimizing TTFB? It’s all about starting sooner, not finishing sooner. Having a fast response time can be just as important as a fast load time.
We want your pages to render quicker (not necessarily just to download quicker). The sooner your page renders, the faster the perceived load will be for users. This is why JS loading is such a finicky matter. Some items should load first, others should all be deferred so they don’t get in the way of critical JS items!
So decide…are you speed-optimizing your site for page scores or for users? (And FYI, it’s possible to do it for both…that’ll be a whole other guide later.)
Aren’t there any exceptions?
As with all things, yes. There are indeed exceptions but they are few and far between and still I wouldn’t recommend you to do it if you wanted a hassle-free caching experience.
Combining CSS/JS from the same theme or plugin makes sense!
If you’ve ever had a theme or pagebuilder plugin offer to combine its own CSS or JS. Yes, please enable that. It makes sense. As all CSS and JS coming from one extension is already compatible/harmonious with itself. Not only that but it can combine them natively without requiring extra server processing or mechanism to manage. It’s like choosing whether to carpool with roommates, or with friends that live all over town.
Combined CSS/JS files sometimes cache better
The key word is “sometimes”. Sometimes the combined file is more likely to hold it’s long expiry time, or hit Cloudflare’s DNS cache better. It depends on different scenarios. It’s always worth a shot if you’re not happy with your situation. The general idea is that the CSS file is cached on the user’s computer and no longer needs to be downloaded on subsequent requests. Only issue left is that even with this, your first load will still be slower as the merged CSS isn’t cached yet. Check your GA stats and if most visitors hit less than 1.5 pages, I probably wouldn’t merge.
Combining CSS/JS is worth it for small files
I especially don’t like when you combine a bunch of large 20kb CSS/JS files to make a giant 1MB file. But if you have a bunch of 0-3kb CSS/JS files, I think it’s ok to combine those. This is logical as small files cost more in DNS lookup time than they do in actual processing time.
Combined CSS/JS files sometimes has less conflicts
This has more to do with conflict resolution than performance. Sometimes, you may have a bunch of CSS or JS files conflicting with each other and breaking the site design or functions. Sometimes combining fixes that. It’s random but I’ve seen it happen.
Combined CSS/JS can speed up small sites when placed in-line
On really small/lightweight sites, the DNS resolution time is longer than the actual load time for the tiny CSS/JS files. In cases like this, it might be a good idea to just combine the CSS/JS code and place it inline with the html.
In this case, you’re speeding up the site not by combining CSS/JS but by reducing the number of HTTP requests. Again, this is only recommend for really lightweight pages! If you’re total CSS and JS is like 10kb or less, you may be a good candidate for this tactic.
Jos Klever
Hi Johnny,
There’s a mistake about HTTPS and HTTP/2. HTTP/2 requires HTTPS and not the other way around. So the fact that HTTPS is implemented everywhere and became the new “standard”, doesn’t mean that HTTP/2 is used. Many servers are still not HTTP/2 ready at the moment.
Even this page is loaded via HTTP/1.1. You can check it yourself via Chrome Dev Tools for example: go to the Network tab and add the Protocol column.
A HTTP/2 check does say that your server is supporting HTTP/2, but your not using it yet on your website.
Fred
Hi,
That is not true, this page is loaded over HTTP/2, except some external files, such as Gravatar and Google Analytics. But that is out of control of the website owner..
Johnny
Thanks for clarification, Jos. Someone else reminded me the other day too but I haven’t gotten the chance to correct it yet! Will do.
Kathir
great post, yes i agree combination is good for speed tests only. but in real time whenever i check my blogs in pc or mobile its always take time to render and sometimes css doesn’t load properly.
I was wondering why its was, i got to know reason behind this through this post.
i will avoid it. thanks for the post.
PingSunday
Dear Johnny,
My website is so light. No JS, and no huge CSS. So should I disable CSS, JS Merged?
I’m using Autoptimize + Async JS, should I disable both?
Johnny
If your site is really light, merging is probably better. 🙂
John
Is minification part of the same process or completely different?
Johnny
Merging means to combine multiple files into one. Minification means to remove all the empty spaces in the file so that the code is clumped all together. Imagine if someone wrote you a long message but without using any spaces, it would certainly save space and while still legible for machine, it’s not as friendly to the human eye. They are 2 separate processes but nowadays, many “combine” mechanisms will also include minification as well since they’re already processing the file.
Imagine if you’re changing one part of your car and decided you might as well change another nearby part as well since you’ve already got it opened up. The logic is somewhat like that.
maxi
I can understand there are some cases where merging is not advised.
But this titles tries to imply merging is all bad.
Looks like a personal preference here. Sorry, this is NOT an advice to follow. It is an idea worth looking at, though. SOMETIMES.
Johnny
I’m trying to imply that merging is more bad than good. Yes, it’s personal preference…but preference built over years of optimizing sites for performance. I’m not against refactoring or code-reorganization. Also not against CSS/JS load optimization. What I am against is wasting server processing time for the chance of MAYBE slightly improving your load times and appeasing silly page scores…while risking style/function breaks and increased initial paint times.
But as always, people are welcome to choose as they wish…those with more skills have more options and freedom to “break the rules”. For everyone else who doesn’t understand either or, my advice is absolutely the most safe and sound. Perhaps you can sit on the speed optimization groups and help hundreds of users every week diagnose broken style/functions issues due to merging. And from there, make your decision whether it’s even worth it in the first place.
Zia Ahmad
Thanks for sharing so much valuable content with us.
Martin
I serve different CSS files for different parts of my site, e.g. the style.css for all sitewide CSS and post.css only for single posts, etc. All these files are minimal but below 20kb. When I activate combine CSS in LSC plugin, I see it creates separate combined CSS files depending on the section I am in, e.g. style.css and post.css only for single posts (and a further 50-60kb for block editor! I hope the option to load only the CSS for the blocks in use comes soon!). Would you recommend to combine these small files?
Johnny
I don’t know your site so I can’t recommend blindly but generally, I hate combining.
Felice
Very interesting article, and comments too.
Glad to read, I was thinking about merging the code but I had doubts.
And each website has a “story in itself”.
Not all the solutions could be right for everyone.
My website doesn’t have many visits, so for the moment, “I let the hand”.
Marty Karr
I found this site by chance after spending countless hours combining multiple (deferred) js files into one js file thereby hoping to increase website page speed in significantly lowering requests to the server. However, in spite of everything I’ve tried from maintaining proper order whether combining multiple js files into one or two js files, when all is said and done, my website still fails to display properly. Needless to say, after reading this post, I am wondering if I have been wasting my time even though for whatever reason I cannot get this to work. I am also wondering why there still exists so much (mis)information on the Internet recommending this practice in light of HTTPS and HTTP/2 whereby (if I understand this correctly), most servers are now able to handle multiple requests as opposed to one at a time (as b4) whereby combining files is no longer required. If such is the case then why do sites like HubSpot Website Grader, GTmetrix, Google PageSpeed Insights, etc., continue to promote this practice of combining CSS/JS files? It just doesn’t appear to make sense. Also, where online can I test my page load speed that provides an accurate assessment thereof?
Johnny
Web server technology improves faster than page speed scores. The same way that computer/internet technology advances faster than what schools can teach. By the time the books are printed, it’s kinda outdated!
Marty Karr
Regarding my previous comment, I should have also stated that I have previously combined both CSS/JS files with success on a multi-page website whereas I am now working on tweaking a one-page website designed/developed using bootstrap 4 where I have been unable to successfully combine CSS/JS files whereby the website fails to properly display as it did before combining JS files. Figure?
Marty Karr
‘Web server technology improves faster than page speed scores. The same way that computer/internet technology advances faster than what schools can teach. By the time the books are printed, it’s kinda outdated!’
Understood but this still doesn’t explain why sites mentioned in my initial comment continue to operate promoting dated information. In my opinion, they’re performing a disservice to their viewers no different than promoting fax machines today for everyday business when facsimile should have gone the way of the dinosaur 20 years ago given digital technology. As popular as fax machines may have been, I never once used a fax machine back in the 90’s given the plethora of illegible and poor reproductions found to be acceptable. Unfortunately, this mindset or fascination with fax machines has continued to this day which I find incredible. In contrast, I have been an avid user and advocate of electronic digital technology since Adobe Acrobat first debuted back in the 90s whereby I have been using electronic PDF forms with continued success in email file attachments. In reality, a facsimile can’t even begin to hold a candle to digital technology and never could. Sorry for the rant. I guess I’m just sick and tired of seeing the public and private sector rely on dated technology wasting precious time completing common everyday tasks that can be completed in a fraction of time using digital technology to achieve results every bit as good if not better than what they’re accustomed.
Joe
I had issues with combing CSS files using SG optimizer. For me, this is sound enough advice to just disable the combine CSS files option, rather than bother to find work around.
For the lay person, who does not have time to test every option I think NOT combining CSS files, is probably the best option.
Yvette Boye
Have just received an SEO Audit report from Ahrefs saying my CSS file size is too large. Is using Autoptimize combined with GeneratePress. After reading your article I am thinking of checking off for combining files for css.
I was using the default settings recommended from GP https://docs.generatepress.com/article/configuring-autoptimize/, but maybe the two checking off for combined choices for my website is not so good?
Johnny
Don’t combine CSS. It’s archaic practice at this point. I’ve only said this 800 thousand times.
Yvette Boye
Okidoki! You are the best!
Truss Genius
@wpjohnny man somehow I ended up on your site and finally read something that made sense. After unchecking those settings on wprocket i resolved my Cumulative Layout Shift errors. Thank you
Orizel Han
Thank you mate… such a good information! Finally, I changed my mind because of some reason here! you are the best
Johnny
I *heart* you. I hope you experience faster snappier page loads because of this.
Hank Wilson
Hi, Johnny.
I have 4 CSS files that are larger than 10k belonging to the page builder(Elementor) and the other 10 smaller CSS files, of which some are even less than 1k. Please tell me, what should I do? Should I exclude the 4 larger files and merge the remaining smaller files?
Johnny
You should read the title of this post.
JetGuy
Great article, but do not agree with you 100%. Your approach does not seem to take into account several factors such a CMS, theme, performance plugin, and CDN used (and their built-in customizable functionalities).
We are combining and deferring both our CSS and JS files and are not experiencing any significant issues. And yes, our website’s performance is great.
It would be great to see your article converted into data (i.e., a performance comparison table) with caveats and conditions attached, of course, so we can make a more educated decision on your topic. In my book “Opinions confuse, data convinces.”
Happy New Year!
Johnny
Seems like you didn’t actually read (or understand) what I wrote. I’ve already accounted for with and without combining CSS. Also…you completely misunderstood what my “approach” was. Which is to code your shit manually and avoid bloat in the first place so you don’t have to do any of this crap.
The only data anybody needs is to play with their own site and see what they like. Nothing else matters. (But of course…if I optimized your site, I’d probably 100% do it differently than you.)
Happy New Year!
JetGuy
Hey Johnny,
Didn’t meant to rough up your feathers.
If you feel so strongly about not combining CSS and JS files, can you explain why SiteGround is highly recommending the combination of these files via their plugin, SG Optimizer?
Would love to see you guys present your arguments and data.
All good!
Johnny
I’m not in their plugin meetings, so I don’t actually know. But if I had to guess:
– They want users to optimize things using their plugin, and not with other plugins (that are more resource intensive).
– They know users care about page scores and measure webhosts by page scores. And so they focus on optimizations that result in higher page scores.
As for “Present your arguments…” – I already did this. The whole guide is my argument. But I say you do whatever you want and live happy.
Web Master of the Universe
I just love how Johnny gets angrier and angrier over the years in these replies. He sounds like me.
I guess this shows lockdowns really will change a man.
That said, combining CSS via Breeze Caching was causing some of my images to load all wack. Uncombined, all good. My site is fixed.
And get this, I NEVER KNEW because I had “caching disabled for logged in users”. Check on new browser logged out and was like, what site is this?
Uncombined and page speed not changed/maybe split seconds faster on full load when I compare historical GTMetrix saves.
Tried the same with JS and it was a LOT slower so I went back to combined JS. Not sure why and it is nearly 6am so I won’t bother.
But this article was a good case for why combining CSS is pointless in today’s world. All it did for me was break my site display.
Brent Alexander
*Inspects code on wpjohnny.com and sees that Johnny uses LiteSpeed to minify JS files*
Source checks out.
Johnny
And if you actually read the whole guide…you’d know my site fits perfectly under one of the listed exception scenarios…”Combining CSS/JS is worth it for small files.”
Please try reading things in full before commenting. 🙂
Brent Alexander
I hear yah and agree with yah 100%. I just thought it was a funny take. Thanks for the WP wisdom Johnny!
Simon
The amount of hours I have spent helping clients raise their google page speed is madness. This article is a breath of fresh air that more is less especially with http 2.
Aditya Nath Jha
Welp, I will keep combining my CSS and JS files and using critical CSS for speeding up first paint. Thanks for the really long article tho.