如何通过ajax将css注入文档?

Pau*_*ulS 7 css jquery

所以我通过jquery的ajax方法获取数据.检索到的数据如下所示:

<html>
<head>
  <style>
  body {
     color: red;
     font-weight: bold;
  }

  #someElement {
     color: blue;
     padding: 1em
  }
  </style>
</head>
  <body>
     <div id="header">Super</div>
     <p>blah blah blah</p>
     <div id="footer">Stuff</div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

如何提取样式并将其插入到执行ajax调用的当前文档中?我尝试了各种各样的jquery咒语,但它没有去.我现在通过正则表达式提取css但不确定如何将css放入当前页面:

$.ajax({
    url: '/template.html',
    success: function(data) {
        $("#header").html( $(data).find('#header').html() );
        $("#footer").html( $(data).find('#footer').html() );

        var re  = /<style>((?:[\n\r]|.)+)<\/style>/m;
        var css = re.exec(data);

        // What to do with the css??

        return;
    }
});
Run Code Online (Sandbox Code Playgroud)

我最初有一个样式表,然后简单地执行以下操作:

    if($.browser.msie) {
        $('head').html(
            '<link rel="stylesheet" href="http://c.this/template.css" type="text/css" />'+
            $('head').html()
        ); 
    }
    else {
        $('head').prepend('<link rel="stylesheet" href="http://c.this/template.css" type="text/css" />');
    }
Run Code Online (Sandbox Code Playgroud)

除了在IE8中,它会导致一些问题.

Mar*_*man 1

您可以使用正则表达式来.filter()查找<style/>标签,而不是使用正则表达式,只需从那里document.getElementsByTagName("head")[0]添加HTMLStyleElement

$.ajax({
    type: 'POST',
    url: "/echo/html/",
    data: {
        html: postHtml
    },
    success: function(data) {
        var style = $(data).filter("style").get(0);
        document.getElementsByTagName("head")[0].appendChild(style);
        $("#header").html($(data).filter('#header').html());
        $("#footer").html($(data).filter('#footer').html());
    }
});
Run Code Online (Sandbox Code Playgroud)

jsfiddle 上的工作示例

在 IE8/9、chrome、firefox 上测试