Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add stylesheet to Head using javascript in body

Tags:

javascript

css

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?

like image 229
Rahil Pirani Avatar asked Aug 06 '12 18:08

Rahil Pirani


People also ask

Can you load a stylesheet in the body?

For example, the stylesheet link type is body-ok, and therefore <link rel="stylesheet"> is permitted in the body. However, this isn't a good practice to follow; it makes more sense to separate your <link> elements from your body content, putting them in the <head> .

How do you add a style to a head tag?

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.


2 Answers

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)

like image 165
vittore Avatar answered Sep 27 '22 21:09

vittore


This will do what you want in an intelligent way. Also using pure JS.

function loadStyle(href, callback){     // avoid duplicates     for(var i = 0; i < document.styleSheets.length; i++){         if(document.styleSheets[i].href == href){             return;         }     }     var head  = document.getElementsByTagName('head')[0];     var link  = document.createElement('link');     link.rel  = 'stylesheet';     link.type = 'text/css';     link.href = href;     if (callback) { link.onload = function() { callback() } }     head.appendChild(link); } 
like image 22
Eddie Avatar answered Sep 27 '22 20:09

Eddie