One big javascript file or multiple smaller files?

64,722

Solution 1

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.

Solution 2

One big file. You should minify the code when it goes to production and compress it if its large. You want to make as few requests to the server as possible to improve page performance

Solution 3

It's best to separate it out, but not get overzealous. That way you can reuse your library code later. Also, everyone likes working with separate files more because it keeps things more organized.

That said, it's also best to give the user one compressed file so that everything can be cached easily, and this also reduces the number of page requests. Rails 3 does this automatically in the asset pipeline, for example. You can write a script to run your favorite compressor. But you shouldn't sacrifice code readability for this -- you can have your cake and eat it too!

Solution 4

One big file or two files: one small and one big. To be clear, during the development it's good have separate files – maybe using something like requireJS. But when you deploy it, it's good compress everything in one file, in order to reduce the HTTP latency and requests.

I mentioned two files. In some cases, it could be good having one small file, that takes care of the "bootstrap" operations, meanwhile the "big file" – especially if it's really big – is downloaded. This is useful especially for the first access, because users doesn't have your files cached yet.

Solution 5

As a rule, I go with as few as possible simply to reduce the number of requests made to the server.

Share:
64,722
Jason Silberman
Author by

Jason Silberman

Updated on March 06, 2020

Comments

  • Jason Silberman
    Jason Silberman about 4 years

    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.