tags:

views:

1820

answers:

3

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 :

  • the css in the popup belongs to the popup and may be coming from a different environment altogether
  • it is dynamic and i dont want to put it in the parent page unless i absolutely have to
  • i planned for it to work like this and it doesnt! :-(
+8  A: 

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");
Shog9
this looks great. AFAYK are these all 'supported' ways of doing this or is this at all hacky? it looks very promising but i'm worried about the one browser that won't let me do this.
Simon_Weaver
They're all valid, but the only way to know for sure if a given browser reacts to the changing DOM correctly is to try it. The last two (thanks, gs!) come with an additional caveat: if your server is misconfigured and sends your CSS down with the wrong MIME type, Firefox will ignore it unless your page is in quirks mode.
Shog9
works great : $('<link rel="stylesheet" type="text/css" href="'+myStylesLocation+'" >') .appendTo("head");
Simon_Weaver
A: 

Anyone can suggest how to do the same with regular js code?

A: 

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

Sorry, meant to add this as a comment to Cris Rus' question.