Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing gzip compressed CSS and JS in HTML/JSPs

Tags:

html

jsp

gzip

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>
like image 463
Saket Avatar asked Jul 14 '12 19:07

Saket


People also ask

How do I gzip CSS and JavaScript files?

htaccess file. Then load an html or js file via the server and check the headers for "Content-Encoding", if it says gzip or deflate, it is enabled. You need access to your vhost/server config to globally enable compression. You don't need to prepare your files, they're compressed automatically on request.

How do I gzip a html file?

In your browser: In Chrome, open the Developer Tools > Network Tab (Firefox/IE will be similar). Refresh your page, and click the network line for the page itself (i.e., www.google.com ). The header “Content-encoding: gzip” means the contents were sent compressed.

Can browser read gzip?

gzip is commonly supported by web servers and modern browsers, meaning that servers can automatically compress files with gzip before sending them, and browsers can uncompress files upon receiving them.


2 Answers

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.

like image 93
Beachhouse Avatar answered Nov 13 '22 10:11

Beachhouse


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>
like image 31
Moin Zaman Avatar answered Nov 13 '22 12:11

Moin Zaman