Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Javascript/CSS into one file or two for better optimization

I am currently working on an c# application that minimizes and combines javascript/css asynchronously in the background to load on to the page which completed. Once the combined minimized file(s) are created, they are saved on to disk and all subsequent requests to the page will load this file.

The reason for this is to assist with performance on the page. I have a concern though, what if the combined file is large, eg 200 kb. Would it be better to combine in to 2 files if this was the case and have 2 separate http requests? The file will be gzipped and cached.

like image 977
amateur Avatar asked Dec 13 '22 16:12

amateur


1 Answers

Well, there are two main schools of thought.

The first, is reduce the number of HTTP requests as much as possible. This would say to reduce ALL CSS files down to one monster. It's better to download 400kb once, than multiple 50kb files. (and the same for JS).

The other is to combine where necessary, but no further. If you have 100kb of CSS that's only needed on one section of the site, there's no reason to slow the rest of the site down for your users. This is especially true for JS since there are lots of sites that include jQuery (for example) on every page because 10% of the site uses it.

My take on it is a combination of the two. If I use code on about 50% of the site or more, I include it in the "master" file. If the code is small (less than 5kb or 10kb), I include it in the master file. Otherwise I split it to separate files.

The whole reason for any of this is to make the user experience better. You could do a giant brute force and load all css and JS in 2 respective files every page load (sure it would be cached). But if the landing page doesn't need 50% of that code, you're needlessly slowing down the page with the biggest impact.

And that's why I believe that the best solution to this problem is to have a human analyze the situation. They can look for duplicates and abstractions. They can look at the needs of the page/site and determine the best scenario. Unless you want to make your program do that (which would be difficult), it's not going to give the best result (but then again, there is a difference between good and good-enough)...

That's my $0.02 anyway...

like image 138
ircmaxell Avatar answered Jan 26 '23 22:01

ircmaxell