Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good Coding: modularized js files or one big js file?

Just want to ask the gurus out there about this. I know that CSS files are better merged instead of separated into a zillion files. Does js work the same way? Here's a few points I currently know(or believe...so you can point something out if my belief/understanding is wrong):

  • i know that js is better modularized for easier maintenance
  • it's "risky" to merge all files into one since there are functionalities that you just want to be on a certain page.
  • i know concurrent downloads slow down a page so it's better to just do 1 big file.
  • merging into 1 file might cause problems with variable scoping?
  • i know there are javascript compilers ala bundle-fu or YUI, but is that the answer to all? different files for dev then just 1 file for js?
like image 566
corroded Avatar asked Sep 03 '10 10:09

corroded


People also ask

Is it good to have multiple JS files?

You can write your JS in separate files, but when it comes to deploying, it's more efficient to minify them all into a single file. For each script you load in your browser, you make a round-trip to the server, so it makes sense to minimize those.

Should all my JavaScript be in one file?

To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.

What is better to load one complete JavaScript file on all pages or separate files based on different pages?

It is best to keep separate files or include all files in one file Javascript? To avoid multiple server requests, it is better to group all your JavaScript files into only one.

Should I separate JavaScript files?

You should put your JS code in a separate file because this makes it easier to test and develop. The question of how you serve the code is a different matter. Serving the HTML and the JS separately has the advantage that a client can cache the JS.


2 Answers

You don't need to use the same files for development and production, so you can have the best of both worlds: modularisation for development, and concatenation for deployment. Here's a list of tools for concatenation and minification.

like image 71
Douglas Avatar answered Sep 19 '22 22:09

Douglas


It's a trade-off between the increased overhead of separate files and the chance you're having users download code they'll never use. You should look at how users use your app.

Consider using a build script to concatenate your files.

like image 37
Jason Avatar answered Sep 20 '22 22:09

Jason