100

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?

Rich
  • 5,603
  • 9
  • 39
  • 61
Chandrasekhar
  • 1,205
  • 3
  • 11
  • 17
  • 1
    for command-line solution: install `npm install uglify-js -g` globally and then do `uglifyjs file1.js file2.js -o output.js -c -m` – Praveen Jan 14 '22 at 10:37

13 Answers13

56

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
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • 1
    could this work with handlebars? – Dan Baker May 17 '13 at 00:45
  • 3
    Better to use a task manager like Grunt, Gulp and other stuff like that do do that automatically. Using Grunt I compile my less, typescript, handlebars into a generated folder, then I copy the js/css files to the generated folder as well, in the end I also minify into one js file all the .js files and into one css fille all the .css files. And I have a watcher rerunning that configuration on file change so that I can save a file and refresh the browser and all changes have been applied within 1-3 seconds. – Vadorequest May 09 '15 at 10:25
18

Try the google closure compiler:

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

Tom Gruner
  • 9,635
  • 1
  • 20
  • 26
  • Google: Closure compiler service is deprecated, and will be removed. Please consider running the compiler locally instead. – Martin Ille May 30 '22 at 05:45
18

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.

Prydie
  • 1,807
  • 1
  • 20
  • 30
11

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
Gary Green
  • 22,045
  • 6
  • 49
  • 75
  • 1
    Option B is not recommended because it causes your browser to make many requests for all the small individual .js files (slow) rather than just one request for a bigger .js file (faster). – Mikepote Jun 27 '13 at 08:59
  • 5
    @Mikepote, yes...hence I used the word `include` i.e. don't do – Gary Green Jun 27 '13 at 09:25
  • Ah sorry, I misread your answer. – Mikepote Nov 18 '13 at 10:03
  • 3
    Can you pl give some example here. – Anand Solanki Apr 24 '14 at 11:02
  • Better to use readfile() to avoid the parsing overhead and accidentally getting something interpreted. – Chinoto Vokro Mar 23 '16 at 18:35
9

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.

8

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.

eloone
  • 4,248
  • 2
  • 32
  • 35
7

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
Schism
  • 275
  • 7
  • 15
SasHok.Tk
  • 477
  • 5
  • 3
7

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

Capsule
  • 6,118
  • 1
  • 20
  • 27
  • 5
    There are valid reasons for combining javascript files. For one, it's quite possible that requesting 20 2kb files will take longer than requesting one 40 kb file. – Joel B Jan 21 '15 at 23:59
  • 1
    Which happens how many times per millenium? – Capsule Jan 23 '15 at 04:43
  • 4
    More often than you'd think. Take a look even at the source code for stackoverflow: "...Option B is not recommended because it causes your browser to make many requests for all the small individual .js files (slow) rather than just one request for a bigger .js file (faster)." – Joel B Jan 23 '15 at 22:08
  • I still believe this is a bit of an edge case. Most of the time, you would have a jquery file, some jquery plugins and then your main js file. 5 to 6 files in total, all of them of a reasonable size, justifying the parallel loading. Of course you have to check what you load in parallel. The best solution being a mix of both methods. – Capsule Jan 27 '15 at 12:09
  • 4
    @Capsule I hate to tell you, but the internet is quickly moving from jQuery to MVC JavaScript, loading one file will always be quicker than firing multiple HTTP requests. – Foxhoundn Sep 02 '15 at 07:35
  • 1
    @Foxhoundn the internet is also quickly moving to HTTP2 so it won't really matter anymore. Anyway, jQuery was just an example, you could face the exact same problem with MVC JS – Capsule Sep 03 '15 at 00:13
5

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.

Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
  • Yes, good point. The closure compiler can be tricky if you or the plugin authors do not keep up with good syntax, or if you are trying to debug. But if you use it in the most basic mode it can be helpful. I personally like Dojo a lot and use their build system with dojo projects, it really helps to keep everything in one file. But it is only useful for deployment, not for development. – Tom Gruner Apr 01 '11 at 10:27
4

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.

technoTarek
  • 3,218
  • 2
  • 21
  • 25
4

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

Oleksandr Knyga
  • 625
  • 9
  • 9
  • I've been looking for tools like this for hours but finally this works exactly how I imagined it should work. Simple and straightforward. – Gergely Kovács Apr 29 '14 at 03:55
2

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.

Ardee Aram
  • 4,740
  • 8
  • 36
  • 37
0

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.

Eben Roux
  • 12,983
  • 2
  • 27
  • 48