开发者

How to inject css into a document via ajax?

So I get data via jquery's ajax method. The retrieved data looks like:

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

How do I extract the style and insert it into the current document, which is executing the ajax call? I've tried all sorts of jquery incantations but it don't go. I'm now extracting the css via regex but am unsure how to put the css into the current page:

$.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;
    }
});

I initially had a style sheet then simply did the following:

    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="ht开发者_运维问答tp://c.this/template.css" type="text/css" />');
    }

That works except in IE8 it causes some problems.


Are you trying to parse a third-party's page, by any chance?

If that is not the case, then why don't you just load the CSS independent of the page that calls your ajax. Then it's available to all elemnts on the page - even new ones delivered by ajax.

If you are trying to parse another sites pages, you'll need to develop a proxy service.


Wouldn't you just create a style tag and insert it into the DOM the same way you would insert any other tag?

$('<style type="text/css"></style>')
    .appendTo("head")
    .html("your css text here");

*Have not tried this

EDIT:

Oh I see you are trying to extract css from an HTML page. Is there a way you can get just the CSS without having to load another page?


Instead of using the regex you could use .filter() to find the <style/> tag, from there simply use document.getElementsByTagName("head")[0] to append the 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());
    }
});

Working example on jsfiddle

tested on IE8/9, chrome, firefox

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜