0

I am wondering how people go about appending CSS aswell as removing CSS when it is relevant.

Currently I load pages and append to my documents usually to some other div. This often causes CSS to be mixed into the page for example it would look like this:

<div id="parent">
   <style>
       .child {
           position:absolute;
           width: 100%;
           height:250px;
           border: 1px solid black;
        } 
   </style>

   <div class="child"></div>
</div>

Now, although this works, I have always been told that CSS should be in the head of the page not mixed in with HTML. I have not really understood why but I presume there are valid reasons? Many website optimising tools seem to "recommend" putting CSS in the head, aswell as removing unused CSS.

I am wondering how do people append relevant CSS to the page head for loading content, then also remove said CSS once they no longer need it such a removing the content from parent via replacing it with a new html page for example.

Does any one even do it that way or do people just append the way I currently do it?

4
  • 4
    Typically, all of the needed CSS is loaded on page load. Developers are not removing it. They are changing the class name on the elements to apply the appropriate CSS as needed. Commented Dec 30, 2015 at 22:34
  • So why do optimizing websites often say to remove unused CSS ? =/ Commented Dec 30, 2015 at 22:36
  • 2
    "unused css" like, unused in all of your website, not in a given page. For exemple if you use Bootstrap, there is generaly a lot of css that is never called anywhere in your website. That is "unused css" Commented Dec 30, 2015 at 22:38
  • @magreenberg i presume that was a joke ? Commented Dec 31, 2015 at 1:43

3 Answers 3

1

I have always been told that CSS should be in the head of the page not mixed in with HTML ... website optimising tools seem to "recommend" putting CSS in the head, aswell as removing unused CSS

Usually it is much better to have all your CSS in external .css files, because:

  • Most websites have more than one page, and webpages in a website use most of the CSS rules and properties, having the CSS in the head means you need to change some certain value in the head sections of all webpages in case you decided to change that value, while if your CSS is in an external file you only need to change that value in one place, imagine the mess if you have too many webpages.
  • if you have like 50 lines of CSS repeated in every page that is extra size added to the page size.
  • Many sites give long cache period their static contents, like javascript files, CSS files fonts and images.
  • It is recommended to keep your html as html, keep layout css seperated than the data and the HTML structure -*same thing for javascript inline events onclick, onmouseenter, etc, better to keep them within as event listener within external .js files or between script tags.

Actually webpage speed recommend having your CSS in external files unless you only have very small chunks of CSS unique to that page then put it in head

Back to your code example I've never used such thing and never seen such use, you can put the used inline style in the external .css file and it will just work without the need to include it like that.

as well as removing unused CSS.

If it was unused you wouldn't of written them in the first place, unless if you are using framework like Bootstrap, Foundation, Pure.css, etc.. . As stated in a comment by @Adrian Tombu.


From https://developer.yahoo.com/performance/rules.html

Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests.

The key factor, then, is the frequency with which external JavaScript and CSS components are cached relative to the number of HTML documents requested. This factor, although difficult to quantify, can be gauged using various metrics. If users on your site have multiple page views per session and many of your pages re-use the same scripts and stylesheets, there is a greater potential benefit from cached external files.

Sign up to request clarification or add additional context in comments.

Comments

1

Most tools that analyze CSS usage only analyze the CSS that is used on the page, and at that moment. The tool will look at all of the tags on your page and see what classes in your CSS files are accounted for and in use.

This means that the tool will only look at what you tell it to look at. If you tell it to see about unused CSS on your fancy profile page (page A), but not the map page (page B), the tool will consider any map CSS that you have in your stylesheet unused.

From an optimization standpoint, it is unused and you're wasting bandwidth having CSS related to page B load with page A and if your users will only ever visit page A, then maybe you should consider not loading that extra CSS. However, if you use that CSS on several pages, it could be beneficial to leverage caching that CSS, even if it isn't used on every page, in order to save bandwidth in the long run.

Now, when you say:

Now, although this works, I have always been told that CSS should be in the head of the page not mixed in with HTML. I have not really understood why but I presume there are valid reasons?

And you show code where you are using an inline <style> tag, I think you misunderstand the goal of putting your CSS in the head tag.

Many websites put their CSS in an external stylesheet that is loaded separately from the page. For example:

<link rel="stylesheet" href="/some/place/on/server.css">

Would have the browser load whatever file is at /some/place/on/server.css and try to use it as rules for displaying your HTML content. It would do this without stopping the rendering of the HTML which is good because it means your users don't have to wait for that file to load to be able to see content. It is potentially bad though because it means that until your external stylesheet loads, content may look strange.

Therefore, it is often beneficial to inline a small portion of CSS for the content on your page that is "above the fold" meaning all of the styles that affect the content that your user sees in the viewport whenever they first load the page.

Some articles that discuss "above the fold" optimization can be found here:

Comments

0

Its not a widely used practice to load CSS for parts of the pages in an AJAX call. Most smaller websites load all the CSS on page load. And it makes sense to leverage browser caching for smaller websites.

It is advisable for bigger websites to break down the CSS into more than one file such that different pages mix and match different CSS files. But one has to be really careful about how many files to break that into. The key is to leverage the browser cache as much as possible.

The other pattern is that of BigPipe. This is exactly what you are asking about. An excerpt from the article:

BigPipe breaks the page generation process into several stages:

  1. Request parsing: web server parses and sanity checks the HTTP request.
  2. Data fetching: web server fetches data from storage tier.
  3. Markup generation: web server generates HTML markup for the response.
  4. Network transport: the response is transferred from web server to browser.
  5. CSS downloading: browser downloads CSS required by the page.
  6. DOM tree construction and CSS styling: browser constructs DOM tree of the document, and then applies CSS rules on it.
  7. JavaScript downloading: browser downloads JavaScript resources referenced by the page.
  8. JavaScript execution: browser executes JavaScript code of the page.

After flushing the first response to the client, web server continues to generate pagelets one by one. As soon as a pagelet is generated, its response is flushed to the client immediately in a JSON-encoded object that includes all the CSS, JavaScript resources needed for the pagelet, and its HTML content, as well as some meta data. For example:

<script type="text/javascript">
big_pipe.onPageletArrive({id: “pagelet_composer”, content=<HTML>, 
css=[..], js=[..], …})</script>

At the client side, upon receiving a pagelet response via “onPageletArrive” call, BigPipe’s JavaScript library first downloads its CSS resources; after the CSS resources are downloaded, BigPipe displays the pagelet by setting its corresponding placeholder div’s innerHTML to the pagelet’s HTML markup.

The good thing is it does not need a special server or any modifications to your stack. https://github.com/garo/bigpipe serves a good simple example.

But if you want to go one step ahead, you can have a look at https://github.com/bigpipe/bigpipe which is a web framework level solution for Node.JS.

As far as "removing" unnecessary CSS, the developer has to be careful about removing CSS classes that are not necessary anymore. Many developers would agree how big a nightmare it is to remove a CSS class. It might break somewhere else that you never expect. It is all about clever way of organising your CSS classes, which is beyond writing in an SO answer. If you are looking to remove CSS dynamically after an AJAX, that will never be possible, IMHO.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.