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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With