CSS and Javascript in a single file

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.

Discuss this article with the rest of the community on our Discord server!


Maker Faire Bay Area 2023 - Mare Island, CA

Escape to an island of imagination + innovation as Maker Faire Bay Area returns for its 15th iteration!

Buy Tickets today! SAVE 15% and lock-in your preferred date(s).