Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One big javascript file or multiple smaller files? [duplicate]

Ok, so I have a reasonable size project, where I'm using jquery backbone and a couple of other javascript libraries. I was wondering if I should have one file for my javascript libraries and another for my custom code. Or a bunch of separate javascript files.

like image 495
Jason Silberman Avatar asked Mar 06 '13 00:03

Jason Silberman


People also ask

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 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.

Does JavaScript file size matter?

Like any other file building a web page, JavaScript needs to load before it can function. The size of JavaScript files along with the way these files are delivered both affect the load time.

Should I have multiple JavaScript 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.


2 Answers

It is generally a good idea to have fewer HTTP requests. So you should reduce the number of files as much as is reasonable.

My personal preference is to have three "groups" of JavaScript files:

  1. Core file. Contains functions that are used almost everywhere and other useful page initialisation things.
  2. Module files. Contains code that is used in several places, but not everywhere. Can be dropped in to provide additional functionality. For instance, if you have a script to handle date inputs, you could include it as a module file and add it to pages that have date inputs.
  3. Page-specific files. These files contain code that is only used in one place. The only reason they're added as separate files than as part of the page itself is for cache reasons.
like image 153
Niet the Dark Absol Avatar answered Sep 18 '22 22:09

Niet the Dark Absol


One big file. You should minify the code when it goes to production and compress it if its large. You want to make as few requests to the server as possible to improve page performance

like image 40
Glenn Ferrie Avatar answered Sep 19 '22 22:09

Glenn Ferrie