Combine CSS with JS and make it into a single download!


Now, if you have by any chance worked on page load optimizations, you would know how costly each resource download is.  The more the number of external resources that you refer to, the more the time it takes for the page load to complete. 


Typically, web pages refer to many external CSS and JS files and hence incur many resource downloads.  The advice from the PLT (page load time) gurus is to combine all the CSS files into one and all the JS files into one so as to reduce the number of resource downloads to just two.  This, without any doubt, would help boost your PLT.


If you feel that two downloads still isn't the best, I concur.  In this post, we'll look at a technique to combine CSS with JS and get the resource download count to one!  I discovered this technique while desperately trying to improve the page load time for the pages in Microsoft Office Live.  Read on...


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

Look at the below JS+CSS code snippet...


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


When the CSS parser parses the above content, the HTML comment tokens would be dropped and the snippet would become equivalent to the one below...


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


As you can see above, the CSS parser will get to see only the CSS code and the script code would appear to be within the comments (/* ... */).


 


In similar lines, when the JS parser parses the content, the HTML comment tokens would be treated as line comments (//) and hence the code snippet would become equivalent to the one below...


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


As you can see above, the JS parser will get to see only the script code and the rest of the contents would look like comments.


You can refer to the above content in both the SCRIPT and LINK tags in your HTML page.  For e.g.,


<link type="text/css" rel="stylesheet" href="test.jscss" />
<script type="text/javascript" language="javascript" src="test.jscss"></script>


Note above that both the tags refer to the same source and hence it would be downloaded once and used as appropriate (as CSS and SCRIPT).


To round it off, there is just one more thing that you need to take care of - the response content type - it needs to be set to */* in order to affirm to Firefox that the contents can be treated as anything as appropriate.


I've attached a sample project (created with VS 2005 SP1) that demonstrates this technique.  Enjoy!


 Update: (put in place due to popular misconception) In the actual implementation you will have the JS and CSS files separately on disk.  At runtime, you'll have to combine them by adding the HTML comments appropriately and serve with the correct content type and cache headers.  You should also remember the dynamically built content so that you don't need to rebuild them for each request.  Please check out the attached sample app.  This will ensure that you don't compromise on the readability, maintainability etc. while at the same time taking advantage of the reduced number of network calls.
 


Note(s):



  • If the JS contains any multi line comments it should be removed before combining with the CSS using this technique.

  • This technique has been tested positive on IE6, IE7 and Firefox 2.0.  It may work on other browsers off the shelf or may need minor tweaks.

Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

JsCssUpdated.zip

Comments (26)
  1. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  2. Oh, very interesting technique – thank you for your article!

    Btw, I suppose that it’s possible have some another trick to eliminate CSS at all – instead of writing it using ordinary CSS rules, I think it’s possible to code it directly in JavaScript via manipulations on styles objects (so such file will not rely on specifics of parsers implementation in different browsers).

    Do you think it could be practical?

  3. DAH says:

    Which versions of IE and Firefox?  What about other browsers?

  4. Franklin says:

    Combining it all into JS wouldn’t be practical, as different browsers have different stylesheet doms, and Opera as of 9 didn’t have a stylesheet dom at all

  5. Chitty says:

    In response to: Andrew Sazonov

    Whist I think this is a fine idea, the problem is anyone with javascript disabled would lose their styles too.

  6. This prevents effective caching.  Every time my JS changes, the "CSS" file also has to be downloaded and vice versa.  Separating the files allows them to be separately cached.

  7. Martin Bialasinski says:

    So this depends on specific bug-correcting implementations of the parser that may or may not change in the future. And at least the JS parsing will break with a true XHTML-parser.

    In other words: it is a hack and a future liability to support, if it gets used.

    How about serving gzip’ed files, with an expire header one year in the future. The files will get fetched once, after that the browser will use the ones in the cache without checking with the server. And when the path to the files contains a version number, you can easily deploy a new version of the files.

    Standard, proven techniques. Far better than messing around like described in this blog post.

  8. Jordan says:

    By analogy I bet you could also squeeze your HTML into the same file! Just end the comments with a <!– /* –> line and then start your HTML. –Joking of course.

  9. GaB says:

    Great stuff, thx !

  10. It looks like that, for this to work, you have to have a comment start for each line of CSS.

  11. shivap says:

    @Jeff – I agree.

    @Martin – True – this is a hack.  However, allowing <!– tokens in javascript has been there right from the beginning for hiding it from older versions of browsers and i personally believe the browsers would never break that.  As for <!– tokens in CSS, even the w3C CSS validator accepts it positively.

    @Sjoerd – You can remove the newlines from the CSS content so that you need to have <!– token only once.  I do this in my sample app.

  12. Mike says:

    So after reading all of these comments – which method is better?

  13. shivap says:

    @Mike – I would suggest that you consider this method only if the page load time bothers you much.  If you are already happy with your website’s load time all you need to do is to remember that you can come back to this technique when the load time starts bothering you.

  14. This is an interesting hack, but I would say this is a ‘oh look you can also do this’, rather than a best practice that people should follow.

    The bandwidth advantage you are gaining is minimal in comparison to the obfuscation overhead you are adding to your files…

    Lets say for example that your js file is 2 kb and css file is another 2kb.

    All you are saying is put them both together in a 4kb file…

    So what is the advantage of this? Advantage is you are skipping one request to the server… This ofcourse comes with its trade offs… One is required to sacrifice code readability, modularity and seperate caching of js and css files simply to squeeze out the overhead of one request of a file from the server.

    I cannot see this a good technique.  Js and css are seperate for a reason. One is client side code, the other is design. Keeping design and code seperate makes it all together more maintainable, especially in a team environment where you can have seperate coders and designers… Not to mention that this is not future proof. For future versions of browsers might require the content type of files returned by the server to always be css for css files and js for javascript files due to some security issue that may arise…

    This is an interesting find, but i would suggest that people do not use this in production.

  15. shivap says:

    @Anastasiosyal – thanks for your comment.  Your point about readability, maintainability etc. has already been made and answered – i.e., keep the js, css files separate on disk and combine them at runtime – please check my sample app.

     I agree with your point about future reliability but there are good reasons why browsers won’t break their backward compat as HTML comments were allowed into JS and CSS in the first place with a reason.

  16. I would suggest that you should avoid this technique at all costs… this is going with non-standard features which will hopefully be removed from the two (of many) browsers in the future.

    Take for example the huge security hole in IE6/7 where JavaScript can be placed in an image and still be executed… allowing any site with an image upload feature (gallery) to be compromised by an XSS attack… I am hoping that this security hole will be fixed, and in a similar way, it might fix this potential security hole (a site which allows users customise their profile page with their own CSS could allow anyone to upload any JavaScript!)

    For more info, this is a good overview:

    http://adblockplus.org/blog/the-hazards-of-mime-sniffing

    And for the reality of XSS:

    http://www.betanews.com/article/CrossSite_Scripting_Worm_Hits_MySpace/1129232391

  17. shivap says:

    @Craig – thanks for the pointers.  I’ve posted to sla.ckers.org to figure out whether this technique can be exploited.  

  18. shivap says:

    Copy pasted from sla.ckers.org

    Comment made by trev…

    "I don’t think there is anything dangerous about this technique (users who can upload CSS can run JavaScript already, due to expression() and -moz-binding)."

  19. shivap says:

    Good discussion happening in Ajaxian on this technique… http://ajaxian.com/archives/squeeze-css-and-js-into-one-file

  20. 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…

  21. ekang says:

    I think this is a good idea

  22. Nick says:

    So, if you’re doing this on the server side anyway, why download css and javascript separately from the HTML at all?  Just include it in the page requested by the user.  

    You can still keep separate css, js, and html (aspx/ashx) files and then either write a custom control that outputs the css+js into the html or extend the page parser to do it when it compiles your pages.

    My method does break caching, but so does yours.

    In all fairness, your method is a neat hack, but it’s not a robust solution to the problem.

  23. shivap says:

    @Nick – Combining js and css and keeping them as an external resource, I agree that it will need to be refreshed every time the js or the css changes, but then how frequently do you expect such changes to happen on a production site?  As for inlining them into the HTML, I think the disadvantages here are too obvious to even write further.

  24. Wow, its really cool tips! Thanks a lot!

  25. Dead Krolik says:

    Thanks a lot. Really good tips.

  26. link 【レポート】IE8で互換性の実現や新機能を利用するには? – MSがサイト管理者向けガイド (1) IE8準拠のための見直しポイント | パソコン | マイコミジャーナル — 2009-04-15 (水) 19:20:52 1つのファイルにJavaScriptとCSSをまとめて記述する方法 phpspot開発日…

Comments are closed.

Skip to main content