Thursday, August 19, 2010

Gzip javascript files

To gzip your javascript files, you can use the following ant task (you can add dependencies to your task as needed).
    <target name="gzipJavascript">
           
<gzip destfile="${destination-dir}/combined.js.gz" src="${path-to-your-js-file}/combined.js">
    </gzip>
</target>


and just invoke this from your ant task. Simple.

The output of the gzip process will now be stored in your prescribed directory. I usually store the un-gzipped ones and the gzipped ones in the same resultant directory.


The next thing you need to do is to make sure that your server can serve this gzipped content to the client. To do that, you will have to modify your server.xml appropriately (its location depends on which application server/web server) that you are using. I have been using jboss and hence i will describe what i did for jboss to be able to do it.

In your <jboss-install-location>/server/<domain>/deploy/jboss-web.deployer/server.xml

Put in the following code (the modified parts are in bold)

    <connector  port="8080" address="${jboss.bnd.address}"
         maxThreads="250" maxHttpHeaderSize="8192"
         emptySessionPath="true" protocol="HTTP/1.1"
         enableLookups="false" redirectPort="8443" acceptCount="100"
         compression="on"
compressableMimeType="text/html,text/xml,text/css,text/javascript, application/x-javascript,application/javascript"
         connectionTimeout="20000" disableUploadTimeout="true" />
Now, the next step is to include the javascript file in your web page.





If i have web/javascript/appname/combined.js and web/javascript/appname/combined.js.gz as a result of my various stages of the build process, my javascript include will look something like this




        <script src="/web/javascript/appname/combined.js" type="text/javascript">
</script>     



Note that i specify the include normally as a "text/javascript" and i really dont specify the ".gz" suffix. The application server will analyze the incoming request and if the client can handle gzipped compressed files, then it will server the gzipped files. Else it will serve the normal file.


Since javascript load is blocking call, you should notice load times reduce drastically once you do this.you can also do this compression for other resources such as your html/css files too.

No comments: