Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  139] [ 1]  / answers: 1 / hits: 103100  / 12 Years ago, mon, august 6, 2012, 12:00:00

I'm working with a CMS that prevents us from editing the head section. I need to add css stylesheet to the site, right after the tag. Is there a way to do this with JS, where I can add a script to the bottom of the page (I have access to add script right before the tag) that would then inject the stylesheet into the head section?


More From » css

 Answers
57

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)


[#83815] Sunday, August 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hakeemabramh

Total Points: 234
Total Questions: 109
Total Answers: 109

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;