Combine multiple JavaScript files into one JS file [closed]


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?


Solution 1:

On linux you can use simple shell script 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.

$ ./ some-script.js another-sctipt.js onemore.js

Solution 2:

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.

Solution 3:

Try the google closure compiler:

Solution 4:

You can do this via

  • a. Manually: copy of all the Javascript files into one, run a compressor on it (optional but recommended) and upload to the server and link to that file.
  • b. Use PHP: Just create an array of all JS files and include them all and output into a <script> tag

Solution 5:

I usually have it on a Makefile:

# All .js compiled into a single one.

    @find ./path/of/js -type f -name "*.js" | xargs cat > $(compiled)

Then you run:

make compile

I hope it helps.

Solution 6:

I use this shell script on Linux

Compared to the above scripts it has the advantages of being very simple to use, and a big plus is that you can list the js files you want to merge in an input text file and not in the command line, so your list is reusable and you don’t have to type it every time you want to merge your files. It’s very handy since you will repeat this step every time you want to push into production. You can also comment files you don’t want to merge in the list. The command line you would most likely type is :

$ mergejs js_files_list.txt output.js

And if you want to also compress the resulting merged file :

$ mergejs -c js_files_list.txt output.js

This will create output-min.js minified by Google’s closure compiler. Or :

$ mergejs -c js_files_list.txt output.js output.minified.js

If you want a specific name for your minified file named output.minified.js

I find it really helpful for a simple website.