2

I am a beginner of Javascript. I have done some Python and Java before.

I am not clear when and why we should store codes into different .js files or the same file.

Is there any conventions and rules for this?

Meng Zhang
  • 337
  • 1
  • 4
  • 13
  • This is a very opinion-based question, but you can find a lot of different answers out there. One of the better discussions can be found over here: http://stackoverflow.com/questions/247209/current-commonly-accepted-best-practices-around-code-organization-in-javascript?rq=1 – Cellivar Aug 09 '14 at 20:25
  • I think it depends on how your javascript will be used by a user. Do you use javascript for some webpage or are you using something like XUL-Runner? In XUL i would suggest you put your logic into modules (single JS files). In a "normal" webpage i would suggest putting it all into one file. If your page has some complicated logic just use multiple files for overview's sake. – Flocke Aug 09 '14 at 20:46
  • Learn the [AMD pattern](http://addyosmani.com/writing-modular-js/) and use [Require.js](http://requirejs.org/). – Jared Farrish Aug 09 '14 at 20:47
  • Or have a look at Node and the CommonJS module system. – Felix Kling Aug 09 '14 at 22:48

1 Answers1

0

Well, the main reason of javascript code into different folders is for organization. Similar to Java or Python, or any language, you should organize your code in different files to get a code that any other in your team can read easily.

But in production scope, or better said, in your website, it's a best practice to reduce the number os javascript files for performance reasons. If you have 2 javascript files, the server will send 2 request. In the case that you have 10 or 15 files, the web will have performance problems.

So, in development it's important to have multiple files to organice your code, but in production you can minify then into one. Uglify is a good tool to monify your code into one file.

Hope it helps.

Mario Araque
  • 4,584
  • 3
  • 14
  • 25
  • Yes. It is my problem that splitting codes into different .js files will increase the load of requests. It is not considered in Java and Python. I will see how Uglify works, many thanks. – Meng Zhang Aug 09 '14 at 21:35