Simon_Weaver
Simon_Weaver

Reputation: 146000

How to apply inline and/or external CSS loaded dynamically with jQuery

I have an Ajax control that is loaded into a Yahoo popup using jQuery.

I just use a simple .get request to load the HTML.

  $.get(contentUrl, null, function(response) {
         $('#dialog').find('.bd').assertOne().html(response);
     }, "waitDlg");

Now the problem is that the content that is loaded needs its own CSS which is actually dynamically created. I have a choice of either inlining the or using an external CSS stylesheet.

Testing in Chrome shows that the CSS loaded via AJAX is not evaluated/applied at the time it is added to the DOM using the above code.

Internet Explorer will evaluate an inlined CSS when it just gets stuck in the DOM but Chrome will not. I am currently unable to test in FireFox because of a completely unrelated issue.

Is there any way in jQuery to evaluate a stylesheet that was dynamically added to the DOM as either an inline or ?

There are many reasons I'd like to do this:

Upvotes: 43

Views: 55820

Answers (3)

user406905
user406905

Reputation: 1418

The accepted answer will not work in IE 7 (and buggy in IE 8). the following will work in IE as well as FF and chrome/safari:

var url = 'urlOfStyleSheet.css'
if(document.createStyleSheet) {
    try { document.createStyleSheet(url); } catch (e) { }
}
else {
    var css;
    css         = document.createElement('link');
    css.rel     = 'stylesheet';
    css.type    = 'text/css';
    css.media   = "all";
    css.href    = url;
    document.getElementsByTagName("head")[0].appendChild(css);
}

Upvotes: 27

Toby
Toby

Reputation:

var cssPath = "/path/to/css/";

var linkStr = document.createElement("<link rel='stylesheet' type='text/css' href='"+cssPath+"' media='screen' />");

document.getElementsByTagName("head")[0].appendChild(linkStr);

Upvotes: 1

Shog9
Shog9

Reputation: 159628

Given a path to your stylesheet (or some URL that will generate valid CSS):

var myStylesLocation = "myStyles.css";

...either one of these should work:

Load using AJAX

$.get(myStylesLocation, function(css)
{
   $('<style type="text/css"></style>')
      .html(css)
      .appendTo("head");
});   

Load using dynamically-created <link>

$('<link rel="stylesheet" type="text/css" href="'+myStylesLocation+'" >')
   .appendTo("head");

Load using dynamically-created <style>

$('<style type="text/css"></style>')
    .html('@import url("' + myStylesLocation + '")')
    .appendTo("head");

or

$('<style type="text/css">@import url("' + myStylesLocation + '")</style>')
    .appendTo("head");

Upvotes: 79

Related Questions