CSS and Javascript in a single file

Technology
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.

What will the next generation of Make: look like? We’re inviting you to shape the future by investing in Make:. By becoming an investor, you help decide what’s next. The future of Make: is in your hands. Learn More.

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

ADVERTISEMENT

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

Prices Increase in....

Days
Hours
Minutes
Seconds
FEEDBACK