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

∥☆過路亽.° 提交于 2019-11-28 11:19:42

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);

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.

simplest way (using jQuery that is) is the following:

var cssLink = $('<link />');
cssLink.attr("rel","stylesheet")
cssLink.attr("type", "text/css");
cssLink.attr("href","url/to.css");

If you do it that way then it will work in Safari. If you do it the normal jQuery way (all in one text string) it will fail (the css won't load).

Then you just append it to the head with $('head').append(cssLink);

Thanks Vatos, you gave me a good lead, basically I did what you suggested but used jquery to set the html and append the new style to the head since, safari/chrome would stall when doing innerHTML and document.head was undefined. My code ended looking like this

var cssDefinitions = '..my style chunk goes here';
var style = document.createElement('style');'
$(style).html(cssDefinitions);
$('head').append(style);

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 = "...";

Here's the gig. What Patrick said did not work for me. Here's how I did it.

    var ref = document.createElement('style');
ref.setAttribute("rel", "stylesheet");
ref.setAttribute("type", "text/css");
document.getElementsByTagName("head")[0].appendChild(ref);
if(!!(window.attachEvent && !window.opera)) ref.styleSheet.cssText = asd;//this one's for ie
else ref.appendChild(document.createTextNode(asd));

InnerHTML is deprecated and shouldn't be used for such a thing. Furthermore it is slower too.

Besides the style tag based versions above, you can also add styles using javascript directly:

var style = document.getElementById('some-style-tag');
var sheet = style.sheet;
sheet.insertRule('.mydiv { background-color: ' + color + '; }', sheet.cssRules.length);

This has the advantage of being able to use variables without having to resort to cssText/innerHTML.

Keep in mind that on webkit based browsers this can be slow if you are inserting a lot of rules. There is a bug open to fix this performance issue in webkit (https://bugs.webkit.org/show_bug.cgi?id=36303). Until then, you can use style tags for bulk inserts.

This is the W3C standard way of inserting style rules, but it is not supported by any version of IE: http://www.quirksmode.org/dom/w3c_css.html

I know it's an older topic, but thought someone would benefit. I too needed to load css dynamically into my page (before everything rendered onload, according to included "component" templates):

var oStyle = $("<style />");

oStyle.append("@import url(" + sTemplateCssUrl + ");");
oStyle.attr("type", "text/css");

$(document.head).append(oStyle);

I tried appending to document.head with a one-line approach -- worked in IE 10 and Chrome, but not in Safari. The approach above worked in all 3.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!