How to Compile JS & CSS to one file for best performance

Written by Garry Lachman (Admin). Filed under Developer Tools, JavaScript, jQuery. Tagged , , , , , , , , , , , , , . Bookmark the Permalink. Post a Comment. Leave a Trackback URL.

Hey,
To get the best performance on your website you need to reduce external call like js & css files.
I build little BASH script that compile all your files to one JS file and one CSS file.

We will use some tools like : Google Closure & dos2unix

1. Create “build” folder in your application.
2. Create the files “js_list.txt” and “css_list.txt” and write line by line all your js & css files.
3. Download Google Closure and copy the file “compiler.jar” to this folder.
4. Create the file “build.sh”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/bin/bash
# (c) Copyright by Garry Lachman - http://www.garry-lachman.com
# GNU/GPL
echo "" > full.js
echo "" > full.css
# JS
echo -e "\nBuild JS\n----------------"
while read line ; do
        JS_FILES[$index]="$line"
        index=$(($index+1))
done < js_list.txt

for f in "${JS_FILES[@]}"
do
        cat "../js/$f" >> full.js
        echo ";" >> full.js
        echo -e "* $f"
done

#CSS
echo -e "\nBuild CSS\n----------------"
index=0
while read line ; do
        CSS_FILES[$index]="$line"
        index=$(($index+1))
done < css_list.txt

for f in "${CSS_FILES[@]}"
do
        cat "../css/$f" >> full.css
        echo -e "* $f"
done

echo -e "\n"
echo -n "Compile JS"
java -jar compiler.jar --language_in ECMASCRIPT5 --compilation_level WHITESPACE_ONLY --js full.js --js_output_file full-compiled.js
echo " - Done"
echo -n "CSS Dos2Unix Format"
dos2unix full.css full.css
echo -e "Moving Compiled Files"
cp full.js ../js/full.js
cp full-compiled.js ../js/full-compiled.js
cp full.css ../css/full.css

5. I use the parent folders “js” and “css” but you can change it to your folder, just replace “../js/” & “../css/” to your path
6. Executing permission:

1
chmod +x build.sh

7. Run the code

1
./build.sh

You will see the output like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@web-serv build]# ./build.sh

Build JS
----------------
* flash_wrapper/swfobject.js
* jquery.tools.local.min.js
* jquery.dropkick-1.0.0.js

Build CSS
----------------
* style.css
* components.css

Compile JS - Done
CSS Dos2Unix Formatdos2unix: converting file full.css to UNIX format ...
dos2unix: converting file full.css to UNIX format ...
Moving Compiled Files

Now check the files: full.css & full-compiled.js

Have fun :)

Share

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*