Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add CSS to <head> with JavaScript?

Is there a way to add css from a string in the javascript file to the head of a document with javascript?

Let's say we have a webpage, which has a lightbox script, this script requires a css file to function.

Now adding this css file with <link> will make the css file download even for people that don't have js enabled.

I know that I can dynamically load the css file with the script, but that also means that there will be 2 http requests, and in cases where there is little to no css in the file I find this inefficient.

So I thought to myself, what if you could put the css that you have in the css file, into the script, have the script parse the css and add it into the head, or even better just have the script add the css directly into the <head> of the document.

But I have found nothing online that suggests that this is possible, so is it possible to add css to the head with js?

Edit + SOLUTION:

I edited roryf's answer to work cross browser (except IE5)

Javascript:

 function addcss(css){     var head = document.getElementsByTagName('head')[0];     var s = document.createElement('style');     s.setAttribute('type', 'text/css');     if (s.styleSheet) {   // IE         s.styleSheet.cssText = css;     } else {                // the world         s.appendChild(document.createTextNode(css));     }     head.appendChild(s);  } 
like image 735
Timo Huovinen Avatar asked Oct 13 '10 09:10

Timo Huovinen


People also ask

How do you add CSS to your 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.

Can you add CSS to JavaScript?

JavaScript can also be used to load a CSS file in the HTML document.

Can you modify CSS with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

Where do I put CSS JavaScript?

You should put CSS in the <head> because that's what the specification says do to. If you have more than one CSS file, they will be loaded in the order you put them in the code. If there is style in the second CSS file, it overwrites the style in the first; That will happen by design.


1 Answers

Edit: As Atspulgs comment suggest, you can achieve the same without jQuery using the querySelector:

document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>'; 

Older answer below.


You could use the jQuery library to select your head element and append HTML to it, in a manner like:

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />'); 

You can find a complete tutorial for this problem here

like image 126
thomaux Avatar answered Oct 06 '22 20:10

thomaux