Add stylesheet to Head using javascript in body
Update: According to specs, the link
element is not allowed in the body. However, most browsers will still render it just fine. So, to answer the questions in the comments - one really has to add link
to the head
of the page and not the body
.
function addCss(fileName) {
var head = document.head;
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = fileName;
head.appendChild(link);
}
addCss('{my-url}');
Or a little bit easier with jquery
function addCss(fileName) {
var link = $("<link />",{
rel: "stylesheet",
type: "text/css",
href: fileName
})
$('head').append(link);
}
addCss("{my-url}");
Original answer:
You don't need necessarily add it to the head, just add it to the end of body tag.
$('body').append('<link rel="stylesheet" type="text/css" href="{url}">')
as Juan Mendes mentioned, you can insert stylesheet to the head instead
$('head').append('<link rel="stylesheet" type="text/css" href="{url}">')
And the same without jQuery (see code above)
Why don't we import css in a div?
That document you link to is a 10-year-old draft, and far from the latest. Now, if you look at the latest revision of the Style Attributes spec, which is a 2010 Candidate Recommendation that covers basically the same inline style declarations that we use every day, you won't find any @import
rules mentioned anywhere anymore.
This means they took it out, presumably because it didn't make sense in retrospect, or it was difficult to implement, or some other reason entirely.
How bad is it to put a CSS include in the middle of the body?
<link>
is only permitted in the <head>
section of a document: Document relationships: the LINK element
Related Topics
Filter: Progid:Dximagetransform.Microsoft.Gradient Is Not Working in Ie7
How to Get The Cursor to Change to The Hand When Hovering a <Button> Tag
Align Text Baseline with a Button in CSS
How to Use Absolute Path to Import Custom SCSS, When Using React + Webpack
CSS for a Sidebar Menu That Folds in and Out
How to Position a Background Image in Reveal.Js
CSS Table Border Spacing Inside Only
How to Keep The Width of The Parent Element When Position: Fixed Is Applied
Why Won't Opera (11.00) Display Custom (@Font-Face) Fonts
Using Container-Fluid Within Bootstrap Cause Horizontal Scrollbar
How to Increase Bootstrap 3 Navbar Height While Keeping Menu Height Small When Collapsed
Rails Bootstrap How to Format Form_For (Width Grid Collapses)
Slide Out Panel with Bootstrap
In Sass, What's The Difference Between The @Mixin and @Extend Directives
Reverse Svg Line Drawing Animation