CSS and Javascript in a single file

If you're really crazy about optimizing page load time for your website, here's an interesting trick. By abusing some parser quirks in common browsers like Firefox and IE, you can actually combine a CSS file and a Javascript file into a single download.

The technique relies on how CSS and JS parser behaves in IE and Firefox.
  • When the CSS parser encounters a HTML comment token (<!--) in CSS content, the token gets ignored.
  • When the JS parser encounters a HTML comment token (<!--) in JS content, the token is treated similar to the line comment (//) and hence the rest of the line following the HTML comment token gets ignored

So, if you can combine your JS and CSS files into a single file like the following, the Javascript parser will only see the Javascript code and the CSS parser will only see the CSS code:

<!-- /*
function t(){}
<!-- */
<!-- body { background-color: Aqua; }

You can still keep the files seperate for coding purposes, and then combine them at publish time or on the fly with a simple script, similar to what's commonly done with Javascript obfuscation/compression.

Combine CSS with JS and make it into a single download - Link.

Posted by Jason Striegel | May 3, 2007 10:18 PM
Web | Permalink | Comments (0) Bookmark and Share

Recent Entries

Comments

Newest comments listed first.

Leave a comment



Bloggers

Welcome to the Hacks Blog!

Brian Jepson.Brian Jepson


Jason Striegel.Jason Striegel


Philip Torrone.Phillip Torrone



See all of the books in the Hacks Series!
Advertise here.

Recent Posts

www.flickr.com
photos in Hacks More photos in Hacks

Most read entries (last 30 days)