Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple JavaScript files, combine into one

I am developing in ASP.NET MVC and using multiple JavaScript files. E.g. jQuery, jQuery UI, Google Maps, my own JavaScript files, etc.

For performance, should I combine these into one? If so, how?

like image 383
raklos Avatar asked Dec 16 '22 17:12

raklos


2 Answers

The reason you want to combine many files into one is so to minimize latency of setting up and tearing down http requests, the fewer you make the better. However, many newer browsers are downloading JavaScript files in parallel (still executing sequentially). The consequence is that downloading a single 1Mb file may be slower than three 350Kb files. What I've come to do is to separate my files into three bundles:

  • External lib files (jquery, flot, plugins)
  • Internal lib files (shared by multiple pages)
  • Page specific files (used only by that page, maybe by two pages)

This way, I get the best of both worlds: not an excessive number of http requests at startup, but also, it's not a single file that can't benefit from parallel downloads

The same applies to CSS, each page load three CSS bundles. So in total, our pages download six bundled files plus the main html file. I find this to be a good compromise. You may find that a different grouping of files works better for you, but my advice is don't create a single bundle, unless it's a one page app. if you find yourself putting the same file into different bundles a lot, it's time to re-think the bundling strategy since you're downloading the same content multiple times.

What to use? Martijn's suggestions are on the money. YUI is the most widely used from my experience, that's what we used at my previous and current jobs.

like image 158
Juan Mendes Avatar answered Dec 19 '22 07:12

Juan Mendes


For the question of whether you should, check out the link in Shoban’s comment.

For the question of how:

  • Google’s Closure Compiler
  • Yahoo!’s YUI Compressor
like image 36
Martijn Avatar answered Dec 19 '22 07:12

Martijn