Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

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:

  • the CSS in the popup belongs to the popup and may be coming from a different environment altogether
  • it is dynamic and I don't want to put it in the parent page unless I absolutely have to
  • I planned for it to work like this and it doesn't! :-(
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...