JS - one huge file or many small files? - where to draw a line?

Is there a good rule of thumb as to how big (in size) a JS file should be - that if it grows bigger than this it's good idea to split it into smaller files?



The same size as any other languages (never more than a few hundred lines), and the concat and minify at runtime (using the Closure compiler or the Yahoo libs or whatnot) is what we do.


More files = More HTTP Requests = Slower website


Develop in as many files as you want. Organize your code to keep development manageable.

Then, when you deploy, ship a minified/combined version of the code using a tool like Google Closure

This is what jQuery does. They ship one file, but the actual source code is much more organized.


Less files = less clean code = slower coding. Cost more than bandwidth.

Edit: if you really want to, you may have tool to merge them after you code of course.


All my JS files - one per function plus the libraries - are in one folder outside the public directory, the prioritary ones start with one or two underscores. In my index page, a PHP script from a static server is called. It checks whether or not the compressed JS file exists. If it does not, a scandir is performed on the JS directory, and each file is included in a buffer, then compressed, and put into a single file. And it outputs the content of this file.

If I change/add/delete a js file, all I have to do is delete the compressed file, and it will be recreated at the next load.

The advantage here is that you have a single and optimized http request for the javascript, and still you can divide your scripts in as many files as you wish. The file creation process - which can be heavy - is not used each time the page loads but only when the file is missing. This method is good when like me you use it with an application which never reloads, or doesn't need to load specific functions for specific pages, although there would be plenty of workarounds.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.