Saket
Saket

Reputation: 46147

Referencing gzip compressed CSS and JS in HTML/JSPs

I am using the YUI compressor plugin to compress and gzip JS and CSS files within my Java EE application.

However, I am not clear on how to reference them within my HTML/JSP files.

If I simply use the .gzip reference, the browser obviously complains saying -

Resource interpreted as Script but transferred with MIME type application/x-gzip

The current reference looks like this (which throws the above error):

<script type="text/javascript" src="/scripts/home.js.gz"></script>

Upvotes: 6

Views: 8208

Answers (3)

Alireza Fattahi
Alireza Fattahi

Reputation: 45573

Although you can configure the tomcat to do all gzip for you, I recommend to manually zip your static resources like js and css files and save them on your server as css.gz or js.gz, then you can use a servlet to send these static and pre compressed files to client, when a request came in.

Please see https://gist.github.com/suprememoocow/1570654 for the servlet implementation.

If your server has a built in mechanism for cahing the gzip files, then you can go with it. As far as I find the tomcat (7) does not have this feature yet.

Upvotes: 0

Beachhouse
Beachhouse

Reputation: 5052

What you are seeing is a warning in your browser, it will show this anytime you interpret data differently than the returned content type.

What you are really trying to do is this:

Content-Type: text/javascript
Content-Encoding: gzip

This will remove the browser error, but also make the browser recognize that this file must be uncompressed before use.

Upvotes: 2

Moin Zaman
Moin Zaman

Reputation: 25455

You reference them with the normal .js and .css extensions and check if gzip is working by checking the response headers on the CSS and JS files by inspecting via firebug or developer tools.

Gzipping is typically done at the web server level.

If you're using tomcat you can open the conf/server.xml of your Tomcat installation and add the following to the Connector definition.

<Connector port="8080" protocol="HTTP/1.1" redirectPort="8443" connectionTimeout="20000"
           compressableMimeType="text/html,text/xml,text/css,text/javascript,text/plain,application/javascript,application/json" 
           compression="2048"/>

For Apache look up mod_gzip or mod_deflate

This goes in your root .htaccess file but if you have access to httpd.conf that is better.

<ifModule mod_deflate.c>
<filesMatch "\.(js|css)$">
SetOutputFilter DEFLATE
</filesMatch>
</ifModule>

Upvotes: 1

Related Questions