javascriptcode-separation

All code in one js file vs separating code into multiple js files


By now I've had only one javascript file in my project that contains tons of functions only few of which are used by more than one web page..As the amount of code involved rises I can see the the file gets messy and way too long. I'm thinking of having a separate javascript file for each web page so that:

  1. I don't have to load the one giant javascript file even for those pages that make very little use of it.
  2. The file doesn't get even more messy

But I don't know if this would have any negative that I'm not aware of.


Solution

  • There are a number of options here, focused purely on the side of organizing your files it's worth considering using a library like require.js if what you're working on is fairly big. This however is meant for applications and even though you can easily use it for other things as well the idea is that you restructure your code into stand alone modules which might or might not be sensible in your case.

    If however the javascript we're talking about is tightly coupled with the content of the page and thus in it's very setup not reusable for other pages it can be quite correct to use inline <script> tags rather than external javascript files.

    And one last note, require.js or any setup with multiple javascript will give a slight overhead regarding http requests, but I would not worry about that too much. Require.js or similar libraries will even load this async for you, so all in all it will probably be a bit more efficient than one huge file which possibly isn't used for a big part for any given visitor (though that depends whether visitors will in the end visit all pages or not).