Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple JavaScript files into one JS file [closed]

I am using jquery in my web application and I need to load more jquery script files into a single page.

Google suggested I combine all the jquery script files into a single file.

How can I do this?

like image 991
Chandrasekhar Avatar asked Apr 01 '11 10:04

Chandrasekhar


People also ask

Can you have multiple scripts in a JS file?

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. Also, take a look at, for example, jquery source on github.

Should I put all my JavaScript 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.

Should JavaScript always be in a separate file?

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.


3 Answers

On linux you can use simple shell script https://github.com/dfsq/compressJS.sh to combine multiple javascript files into the single one. It makes use of the Closure Compiler online service so the resulting script is also effectively compressed.

$ ./compressJS.sh some-script.js another-sctipt.js onemore.js
like image 127
dfsq Avatar answered Oct 16 '22 18:10

dfsq


Try the google closure compiler:

http://code.google.com/closure/compiler/docs/gettingstarted_ui.html

like image 35
Tom Gruner Avatar answered Oct 16 '22 18:10

Tom Gruner


Just combine the text files and then use something like the YUI Compressor.

Files can be easily combined using the command cat *.js > main.js and main.js can then be run through the YUI compressor using java -jar yuicompressor-x.y.z.jar -o main.min.js main.js.

Update Aug 2014

I've now migrated to using Gulp for javascript concatenation and compression as with various plugins and some minimal configuration you can do things like set up dependencies, compile coffeescript etc as well as compressing your JS.

like image 18
Prydie Avatar answered Oct 16 '22 18:10

Prydie