Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject css into a document via ajax?

Tags:

jquery

css

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="http://c.this/template.css" type="text/css" />');
    }

That works except in IE8 it causes some problems.

like image 367
PaulS Avatar asked Jun 29 '11 14:06

PaulS


1 Answers

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.

like image 83
T9b Avatar answered Sep 30 '22 12:09

T9b