Suppose I write a site with four pages. These pages have the same functionality (the same JavaScript), but there are differences.

How to organize the code? Is it possible to stuff everything into one file? And how to hang handlers, such as buttons, if they are on one page and not on the other?

  • 3
    Now the guru-angulyarschiki will come running, so we have little time =) In short - on a website with 4 pages, you can not bathe and stuff everything into one file. It's okay that there is no handler on the page where there is no button. - xaja
  • Place all your functionality in one file. Assign one initialization function. In it, check the url of the loaded page. And depending on it, launch certain functions / components. - Visman
  • Roughly speaking: if this is page 1 then initialize script 1? Right? - Anatoly Sivenko

3 answers 3

It is necessary to call only the code that relates to this page.

Scripts can be combined into 5 files (common, plus one per page), or into one file. In general, this is solved by the number of scripts.

var app = {}; (function () { app.utils = app.utils || {}; app.utils.doSmth = function () { // ... } })(app); (function () { app.page1 = { init: function () { // ... } // ... } })(app); // ... 

And somewhere on the page

 <script>app.page1.init();</script> 

Look in the require.js-module loader. It will be very easy to organize the code with it, this is how to fill the boxes: each box has its own balls, where the balls are your js files, and the boxes are pages. Require here acts in the role that these boxes are filled

Here is the documentation

    You put all your code into functions, collect it in one file, and in html you already connect it as a script and call only the functions you need. You can hang on the event in different ways, for example, on jquery

     $(document).ready(function() { $("#buttonSave").click(function(){ alert("Hello World!") }) })