Safari 3 CSS Declarations in an AJAX Response

A few days ago at work I ran into a behavior of Safari version 3.x that I had not previously noticed. Perhaps this is because I have long been aboard the Safari 4 beta train, where the CSS would update normally. Essentially, Safari 3 doesn't load CSS declarations that occur in the body of an AJAX response. They just get ignored. I need different styles applied to various elements on the page that get loaded with the AJAX response.

It turns out Safari 3 is pretty inflexible with regards to this particular web standard, and doesn't like any style declarations in body of the page. It's default behavior is to (ever so helpfully) "move" the style elements into the head of the document, printing a small log to the error console. One could make the case that this is correct behavior, but it's not the behavior implemented by any other browser I know of. Phooey.

To make Safari 3 display the CSS from the loaded AJAX page fragment, it's possible to mimic its native behavior and move the style elements into the head of the page. I did something like (using Prototype):

var myEl = $('MyUpdateEl');

// Safari 3 doesn't "see" the MyStyle CSS element because its declaration is in the body.
// Remove the EXISTING 'MyStyle' style element from the head if it exists.
var style_el = $('MyStyle');
if (style_el) {
    style_el.remove();
}

// Switch out the content.
myEl.update(responseText);

Finally, move the new style element that was included in the response:

// Move the NEW MyStyle element to the head so Safari 3 will show the new styles.
style_el = $('MyStyle'); // This element comes inline with the responseText.
if (style_el) {
    style_el.remove();
    var head_el = Element.extend(document.getElementsByTagName('head')[0]);
    head_el.insert(style_el);
}

This technique could be easily extended to loop through any style declaration blocks in the AJAX response and move them all into the document head. But this worked for my particular situation. :)


Comments

  1. At Nov. 2, 2009 @ 10:40 p.m. Nikhat said:

    Thank you so so so very very very much for this post.

    I had a similar bug and it was driving me nuts.

    Initially i thought that Safari was not loading the css in the ajax response.

    But the code that i was using was scripted by someone else earlier and was working fine elsewhere on the site. It just wasnt working on my page.
    And it was really making me pull out my hair.

    But after reading your post, I checked the earlier page and turns out the original author had just included the styles both in the main page and the ajax response so that his page works in all browsers.

    Anyway long story short, your post helped me a lot. Thanks a ton :-)

Have any thoughts about this post? Add your comment.