0

I separate each module into different files. Sometimes, a module is just a small function. I use RequireJS to load my JavaScript files in production.

My question is, in production, does it make sense to require a lot of small files (will it improve performance)? Is it better to concatenate several files into larger files then require the larger file?

totallyNotLizards
  • 8,489
  • 9
  • 51
  • 85
Daiwei
  • 40,666
  • 3
  • 38
  • 48
  • The short answer is "no". RequireJS has a dedicated optimizer ([r.js](http://requirejs.org/docs/optimization.html)) which creates a production bundle for you – kryger Oct 03 '13 at 15:35

1 Answers1

2

Every small file is an extra HTTP request and that costs a lot of performance. An HTTP request involves a lot of overhead: that's HTTP headers, which today are quite big and they can't be gzipped. In addition to that, browsers usually have a limit of connections that they'd make to one server, thus blocking requests for further requests until previous are done.

Until HTTP 2.0 arrives, you should definitely concatenate all your javascript into one or two big files in production, absolutely. (For example, Yahoo guidelines clearly stated that back in 2007!)

Of course, you should not be doing this manually. Requirejs has optimizations for production, you do not need to do any manual labor. Readability of your code is almost of utmost priority.

Denis
  • 5,061
  • 1
  • 20
  • 22
  • "definitely concatenate all your javascript into one or two big files" be sure to exclude libraries or shared resources, or anything that might need to be loaded on one page but not another. – zzzzBov Oct 03 '13 at 15:02
  • Could you define `a lot of performance`? If I have 10 20KB files versus 1 200KB file, what performance improvement am I likely to get? – Nunners Oct 03 '13 at 15:03
  • @Nunners http://stackoverflow.com/questions/11011023/multiple-small-files-v-s-one-big-file-for-http-requests – ashley Oct 03 '13 at 15:06
  • https://developers.google.com/chrome-developer-tools/docs/network has a nice HTTP request-response timing diagram. – Alexander Pavlov Oct 03 '13 at 15:08
  • 1
    @zzzzBov For things like jquery that that may be true. But for application code, sometimes it is better to add all files to a single bundle even if you are not using all of them at the same page, because this file can be cached once. If you cache correctly, sending these some extra kilobytes in the same request can provide better experience than requesting different files again and again. Depending where you are (eg. requesting data from an US server from outside the US), removing 100-150ms of latency is more important than removing 50kb from the first request. – Natan Dec 02 '13 at 10:32
  • @Natan, I don't disagree with what you're saying. My original comment was really for scripts that must not be loaded on every page such as ones that change the DOM, or autoexecute. – zzzzBov Dec 02 '13 at 14:20