One big javascript file or multiple smaller files?

Jason Silberman picture Jason Silberman · Mar 6, 2013 · Viewed 57.5k times · Source

Ok, so I have a reasonable size project, where I'm using jquery backbone and a couple of other javascript libraries. I was wondering if I should have one file for my javascript libraries and another for my custom code. Or a bunch of separate javascript files.

Answer

Niet the Dark Absol picture Niet the Dark Absol · Mar 6, 2013

It is generally a good idea to have fewer HTTP requests. So you should reduce the number of files as much as is reasonable.

My personal preference is to have three "groups" of JavaScript files:

  1. Core file. Contains functions that are used almost everywhere and other useful page initialisation things.
  2. Module files. Contains code that is used in several places, but not everywhere. Can be dropped in to provide additional functionality. For instance, if you have a script to handle date inputs, you could include it as a module file and add it to pages that have date inputs.
  3. Page-specific files. These files contain code that is only used in one place. The only reason they're added as separate files than as part of the page itself is for cache reasons.