Skip to content

Instantly share code, notes, and snippets.

@iloveitaly
Created February 22, 2011 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iloveitaly/838047 to your computer and use it in GitHub Desktop.
Save iloveitaly/838047 to your computer and use it in GitHub Desktop.
Compress css + js files
compress_web_files() {
JS_OUTPUT_FILE=$1
CSS_OUTPUT_FILE=$2
JAVASCRIPT_FILES=$3
CSS_FILES=$4
generate_js_include() {
echo "document.write('<script src=\"/includes/$1\" type=\"text/javascript\" charset=\"utf-8\"></script>');"
}
generate_css_include() {
echo "@import \"/includes/$1\";"
}
if [[ "$USER" == "Mike" ]]; then
DEVELOPMENT=1
else
DEVELOPMENT=0
fi
if [[ -e $HOME/scripts/yuicompressor.jar ]]; then
CSS_OPTIMIZER="$HOME/scripts/cssoptimizer"
JS_OPTIMIZER="$HOME/scripts/yuicompressor.jar"
else
CSS_OPTIMIZER='cssoptimizer'
JS_OPTIMIZER='/usr/bin/yuicompressor.jar'
fi
if [ $DEVELOPMENT == 1 ]; then
> $JS_OUTPUT_FILE
for file in ${JAVASCRIPT_FILES[@]}; do
generate_js_include "$file" >> $JS_OUTPUT_FILE
done
> $CSS_OUTPUT_FILE
for file in ${CSS_FILES[@]}; do
generate_css_include $file >> $CSS_OUTPUT_FILE
done
# we dont want the server trying to serve the wrong data
if [[ -e "$CSS_OUTPUT_FILE.gz" ]]; then
rm "$CSS_OUTPUT_FILE.gz"
fi
if [[ -e "$JS_OUTPUT_FILE.gz" ]]; then
rm "$JS_OUTPUT_FILE.gz"
fi
return 0
fi
# Darwin is assuming os x
if [[ `uname` == "Darwin" ]]; then
tempFile=`mktemp -t webcompress.xxx`
else
# mktemp on server runs differently than the os x version
tempFile=`mktemp`
fi
# Compress CSS
for file in ${CSS_FILES[@]}; do
# count /'s.. if we are father down in the directory replace ../../../ with ../
if [[ `echo "$file" | perl -ne 'while(/\//g){++$count}; print "$count\n"'` > 2 ]]; then
cat $file | sed 's/\.\.\/\.\.\/\.\.\//..\/..\//g' >> $tempFile
else
cat $file >> $tempFile
fi
done
"$CSS_OPTIMIZER" -lo $tempFile > $CSS_OUTPUT_FILE
# the IE file needs to be compressed
# whitespace causes issues with IE
# we have to do this round-about compression b/c of a bug in cssoptimizer
cp 'css/lib/ie.css' 'css/lib/ie2.css'
"$CSS_OPTIMIZER" -lo 'css/lib/ie2.css' > 'css/lib/ie.css'
# Compress JS
> $tempFile
for file in ${JAVASCRIPT_FILES[@]}; do
cat $file >> $tempFile
done
java -jar "$JS_OPTIMIZER" --type js "$tempFile" > "$JS_OUTPUT_FILE"
# gzip compress, but keep the original core.css in addition to the newly created core.css.gz
gzip -fc "$JS_OUTPUT_FILE" > "${JS_OUTPUT_FILE}.gz"
gzip -fc "$CSS_OUTPUT_FILE" > "${CSS_OUTPUT_FILE}.gz"
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment