Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to include CSS after <head>

Tags:

Apparently adding <link rel="stylesheet" ... in the document body is considered a bad practice by W3C standards. The same for adding <style> blocks in the body...

So are there any standard-compliant solutions to add CSS outside of the <head> tag? Like at the end of the document.

like image 570
Alex Avatar asked May 19 '12 12:05

Alex


People also ask

How do I include a CSS file in my head?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.

Does CSS go in head or body?

As CSS is not document content, it should be in the head. Also every other Web developer will expect to see it there, so don't confuse things by putting it in the body, even if it works!

What is the correct way to include a stylesheet named style CSS in the head of your document?

The <style> element must be included inside the <head> of the document. In general, it is better to put your styles in external stylesheets and apply them using <link> elements.

What is the correct way to include stylesheet?

With an external style sheet, you can change the look of an entire website by changing just one file! Each HTML page must include a reference to the external style sheet file inside the <link> element, inside the head section.


2 Answers

If you only want to include your CSS styles on a specific events, there's nothing stopping you from doing so at the head:

var linkElement = document.createElement("link");
linkElement.rel = "stylesheet";
linkElement.href = "path/to/file.css"; //Replace here

document.head.appendChild(linkElement);

This has the added benefit of adding your stylesheet in an async way, which doesn't block the browser from downloading anything else.

like image 170
Madara's Ghost Avatar answered Oct 27 '22 22:10

Madara's Ghost


One way to solve that issue is to load the CSS with .get() and, appending it to the head tag only when needed:

JQUERY

var css = "foobar.css";
var callback = function() {
  alert("CSS is now included");
  // your jquery plugin for a navigation menu or what ever...
};

$.get(css, function(data){
  $("<style type=\"text/css\">" + data + "</style>").appendTo(document.head);
  callback();
});

The callback function is useful to allow script code that depends on the CSS file to be properly formatted, to run only after the CSS as been added!

like image 23
Zuul Avatar answered Oct 27 '22 20:10

Zuul