Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript file organization and design

Tags:

javascript

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.

like image 470
Ilya Avatar asked Jan 02 '11 00:01

Ilya


People also ask

What is the structure of JavaScript file?

JS (JavaScript) are files that contain JavaScript code for execution on web pages. JavaScript files are stored with the . js extension. Inside the HTML document, you can either embed the JavaScript code using the <script></script> tags or include a JS file.

Does the order of JavaScript files matter?

If I'm understanding your question I think you're asking if it matters where in a file a function/method is defined, and the answer is no, you can define them anywhere in a single source file. The JavaScript parser will read in all symbols before trying to run the code.

How do I manage JavaScript files?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.


1 Answers

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

like image 119
Chris Laplante Avatar answered Oct 12 '22 23:10

Chris Laplante