How do I load css rules dynamically in Webkit (Safari/Chrome)?

16,566

Solution 1

I think it's a better practice to append a "link" tag to the head of your document. If that isn't possible, try to append a "style" tag to the head. Style tags shouldn't be in the body (Doesn't even validate).

Append link tag:

var link = document.createElement('link');

link.setAttribute('rel', 'stylesheet');

link.type = 'text/css';

link.href = 'http://example.com/stylesheet.css';

document.head.appendChild(link);

Append style tag:

var style = document.createElement('style');

style.innerHTML = 'body { background-color: #F00; }';

document.head.appendChild(style);

Solution 2

Straight-up jQuery way (that works on major browsers - including Chrome): http://topsecretproject.finitestatemachine.com/2009/09/how-to-load-javascript-and-css-dynamically-with-jquery/

From the site:

$("head").append("<link />");
var CSS = $("head").children(":last");
CSS.attr({
"rel": "stylesheet",
"type": "text/css",
"href": "url/to.css"
});

Note: the example also includes injection of JS, which can be ignored if you just want to inject a CSS reference.

Solution 3

meh. I don't have enough points to vote up Andrei Cimpoca's result, but that solution is the best one here.

style.innerHTML = "..."; does not work in webkit engines or ie.

To correctly inject css text, you must:

style.styleSheet.cssText = "..."; for ie.

and

style.appendChild(document.createTextNode("...")); for webkit.

Firefox will also work with the second option, or with style.innerHTML = "...";

Share:
16,566
Admin
Author by

Admin

Updated on July 07, 2022

Comments

  • Admin
    Admin almost 2 years

    I currently have issues in Webkit(Safari and Chrome) were I try to load dynamically (innerHTML) some html into a div, the html contains css rules (...), after the html gets rendered the style definitions are not loaded (so visually I can tell the styles are not there and also if I search with javascript for them no styles are found). I have tried using a jquery plugin tocssRule(), it works but it is just too slow. Is there another way of getting webkit to load the styles dynamically? Thanks. Patrick

  • Bayleef
    Bayleef over 13 years
    innerHTML is a deprecated method and should not be used at all.
  • Bayleef
    Bayleef over 13 years
    hmm yes I don't even know why I have written that. I don't remember what I was thinking about when I wrote it.
  • Vitaly Zdanevich
    Vitaly Zdanevich almost 6 years
    document.querySelector('#x').style.sheet is undefined.
  • felixfbecker
    felixfbecker over 3 years
    innerHTML is not deprecated.