11

Really getting into web development and in particular JS so I was wondering what were the best practices in terms of JS file organization and delegation of responsibilities. I ask this because it would make sense to me to have this kind of structure:

  • MAIN PAGE (PHP) (Includes a reference to a central JS file)
  • MAIN Javascript File (Includes a reference to one file containing only error codes in a namespace or a class of B)

While this makes sense to me, I am wondering if I am wrong in my view considering the fact that you can't naturally include a JS file into another unless you do a couple tricks (no, not talking about jQuery). Tricks may mean that this isn't done simply because it doesn't fit with the best of practices for a language but it's not always the case in terms of cross-domain issues. So before I go too deep into sloppy design, I was just curious how you guys divided up the responsibilities or just slopped everything together into one file.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
Ilya
  • 1,215
  • 1
  • 14
  • 25

3 Answers3

10

The best way to handle multiple JavaScript files is to design them like modules. One main JavaScript file should act as a sort of bootloader which kicks off things by setting up your "namespace" (quoted since JavaScript doesn't have classes). Example:

var myNamespace = {};

In each of your modules, you extend the "namespace". This has two benefits:

  • Minimizes globals. In this case, you will have a single global.
  • Easy to mix and match (and reuse) modules, if designed correctly.

Also see this for implementation details: https://stackoverflow.com/a/3722845/221061

Community
  • 1
  • 1
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
  • Thanks. In your case though, I assume that all the code is in one file, you are just cleaning it up by placing each in its own module correct? – Ilya Jan 02 '11 at 02:21
  • You could do it that way, but that kind of defeats the purpose of modules. I would recommend putting each one in its own file so you can reuse them later (the mix-and-match part). – Chris Laplante Jan 02 '11 at 19:55
2

I would split the classes up into modular JS files, matching your domain. Use YUI compressor or other tools to compress JS files and minify them.

Sonny Kwok
  • 21
  • 2
0

One large JS file is really not that "bad" compared to using multiple JS files.

You can compress it on the server if your worried about band width, look into gzip or deflate.

Greg McNulty
  • 1,476
  • 5
  • 28
  • 50
  • 2
    Oh it's not at all about space. Rather, about keeping everything neat and logical. – Ilya Jan 02 '11 at 02:18