[javascript] Combine multiple JavaScript files into one JS file

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?

This question is related to javascript jquery jquery-ui

The answer is


Copy this script to notepad and save as .vbs file. Drag&Drop .js files on this script.

ps. This will work only on windows.

set objArgs = Wscript.Arguments
set objFso = CreateObject("Scripting.FileSystemObject")
content = ""

'Iterate through all the arguments passed
for i = 0 to objArgs.count  
    on error resume next
    'Try and treat the argument like a folder
    Set folder = objFso.GetFolder(objArgs(i))
    'If we get an error, we know it is a file
    if err.number <> 0 then
        'This is not a folder, treat as file
        content = content & ReadFile(objArgs(i))
    else
        'No error? This is a folder, process accordingly
        for each file in folder.Files
            content = content & ReadFile(file.path)
        next
    end if
    on error goto 0
next

'Get system Temp folder path
set tempFolderPath = objFso.GetSpecialFolder(2)
'Generate a random filename to use for a temporary file
strTempFileName = objFso.GetTempName
'Create temporary file in Temp folder
set objTempFile = tempFolderPath.CreateTextFile(strTempFileName)
'Write content from JavaScript files to temporary file
objTempFile.WriteLine(content)
objTempFile.Close

'Open temporary file in Notepad
set objShell = CreateObject("WScript.Shell")
objShell.Run("Notepad.exe " & tempFolderPath & "\" & strTempFileName)


function ReadFile(strFilePath)
    'If file path ends with ".js", we know it is JavaScript file
    if Right(strFilePath, 3) = ".js" then       
        set objFile = objFso.OpenTextFile(strFilePath, 1, false)
        'Read entire contents of a JavaScript file and returns it as a string
        ReadFile = objFile.ReadAll & vbNewLine
        objFile.Close
    else
        'Return empty string
        ReadFile = ""
    end if  
end function

You can use a script that I made. You need JRuby to run this though. https://bitbucket.org/ardee_aram/jscombiner (JSCombiner).

What sets this apart is that it watches file changes in the javascript, and combines it automatically to the script of your choice. So there is no need to manually "build" your javascript each time you test it. Hope it helps you out, I am currently using this.


I use this shell script on Linux https://github.com/eloone/mergejs.

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.


If you're running PHP, I recommend Minify because it does combines and minifies on the fly for both CSS and JS. Once you've configured it, just work as normal and it takes care of everything.


Script grouping is counterproductive, you should load them in parallel using something like http://yepnopejs.com/ or http://headjs.com


I usually have it on a Makefile:

# All .js compiled into a single one.
compiled=./path/of/js/main.js

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

Then you run:

make compile

I hope it helps.


You can use KjsCompiler: https://github.com/knyga/kjscompiler Cool dependency managment


You can use the Closure-compiler as orangutancloud suggests. It's worth pointing out that you don't actually need to compile/minify the JavaScript, it ought to be possible to simply concatenate the JavaScript text files into a single text file. Just join them in the order they're normally included in the page.


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

This may be a bit of effort but you could download my open-source wiki project from codeplex:

http://shuttlewiki.codeplex.com

It contains a CompressJavascript project (and CompressCSS) that uses the http://yuicompressor.codeplex.com/ project.

The code should be self-explanatory but it makes combining and compressing the files a bit simnpler --- for me anyway :)

The ShuttleWiki project shows how to use it in the post-build event.


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.



Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete