📜 ⬆️ ⬇️

Combine javascript and css in one file

If you worked on optimizing the page load, you know how expensive each resource load is. The greater the number of external resources that you access, the longer it takes to load the page.
As a rule, web pages refer to many external CSS and JS files and consequently undergo many resource downloads. The advice from the optimization gurus is to merge all the CSS files and one and all JS files to reduce the number of resources to two. This will no doubt help reduce page load time.
If you still think that these two downloads are not the best solutions, I agree with you. In this article we will look at how to combine CSS with JS and reduce the number of downloads to one. I discovered this method while desperately trying to optimize pages in Microsoft Office Live.

The technique is based on how CSS and JS parser behave in IE and Firefox.
• When a CSS parser encounters an HTML comment symbol (<! -) in the CSS content, the symbol is ignored.
• When the JS parser encounters an HTML comment character (<! -) in the JS content, the character is considered a comment-like line (//), and therefore the rest of the line after the HTML comment character is ignored

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

When the CSS parser parses the above code, the HTML comment characters will be skipped, and the code will become equivalent to the code below ...
/ *
function t () {}
* /
body {background-color: Aqua; }

As you can see, the CSS parser sees only the CSS code, and the script code is commented out (/ * ... * /).

When the JS parser parses the code, the HTML comment characters will be interpreted in the comment line (//), and therefore the code will become like this ...
// / *
function t () {}
// * /
// body {background-color: Aqua; }

As you can see, the JS analyzer sees only the script code, and everything else is noted.
')
To link to this resource, you can use the SCRIPT and LINK tags in your page. For example:
<link type = "text / css" rel = "stylesheet" href = "test.jscss" />
<script type = "text / javascript" language = "javascript" src = "test.jscss"> </ script>

Note that these two tags refer to the same resource and therefore it will load only once, and will be interpreted both as styles and as scripts.

And lastly, there is one more thing you have to take care of - the content type of the response - you need to put * / * to confirm to Firefox that the content can be processed as something suitable.

Source: https://habr.com/ru/post/31122/


All Articles