Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any disadvantages to concatenating all JavaScript files (including vendor)

To minimize the number of requests made to my server and improve load time, I was thinking about concatenating all my JS Files, including vendor js files like angular, jquery-ui, ... It's a common practice to do this, but I often see websites that don't include their vendor JS files in the same JS file. I know that lots of sites use CDNs to reuse a cached version of the JS file that an other page might have used. Howewer, sometimes, they are separate vendor JS files that are served on the same server, for example on Github :

Github

Github has :

  • Frameworks.js that contains Modernizr, jQuery
  • github-...js that contains the JS from Github itself.

Is there a particular reason to do this ? Are they any issues that could appear because you concat all your JS Files ?

like image 965
edi9999 Avatar asked Oct 03 '22 09:10

edi9999


2 Answers

The main reason is to minimise the number of http requests. In a bigger project if you are using some pattern like MV* you might want to abstract each module in an external .js file. This can result in many files 30-40 for example. In that case you might want to concat then into single file.

In a smaller project where you are going to have 3-4 js file, you use then without concatenation. I use requirejs to define modules as AMD and have each module in external file. Then I use requirejs build script to manage dependency and concatenated deployment file.

Good tools to automate this process

  • RequireJS
  • GruntJS
like image 72
Gaurav Jassal Avatar answered Oct 07 '22 19:10

Gaurav Jassal


Depends on how your applicatio is. Hypothetically, say if you have 20 js files of 0.5MB each. Out of which only 2 (1MB) are required on the first page. You might want to keep them separate and combine others. Load the others in deferred mode while on the first page. So, combining files is good when you understand what all to combine. As a general rule, if you have very few files, then it really does not make a very big difference.

some of the things that you should think about before combining javascript files,

when you combine 100 files together. you are cutting down on 99 requests. But you are also doing the following:
* increasing the time it takes to download that single file (and may be blocking loading of an important page)
* account for the time spent in parsing of the additional JS code that we just pulled from the server, when it might not even be required at this point. The javascript engines are getting faster and faster, but it is still true, that a significant amount of time is spent in parsing of the javascript code.

so, in short the answer is - "it is always a trade-off game and knowing your code well helps" :)

http://tomdale.net/2012/01/amd-is-not-the-answer/ is an interesting read on similar lines.

like image 35
v2b Avatar answered Oct 07 '22 20:10

v2b