Thursday, March 24, 2011

What is the best way to handle style tags when loading HTML with AJAX in IE 6 or 7?

Our AJAX framework works such that it sends back a snippet of HTML that might contain a tag. We then take that snippet of HTML and set it to be the innerHTML of an element. In IE 6/7 it appears to ignore the tags and so the returned HTML isn't styled properly.

I'm wondering if other people have run into similar problems, and if so, how they've dealt with them. I know I could use a javascript library (we use YUI) to dynamically get external style sheets, so I could convert this to an external style sheet. Just wondering if there are other ways to fix this.

From stackoverflow
  • Of course the best method is a pure DOM solution, ie use document.createElement to generate all the elements returned by the server.

    However, there is (of course) an IE hack to work around some of the problems presented by innertHTML. Instead of sticking the response straight into the DOM, first create an element, append its innerHTML, then attach it to the DOM.

    function responseHandler(response) {
        var div = document.createElement('div');
        div.innertHTML = response.responseText
        document.getElementById('ZE_ELEMENT').appendChild(div);
    }
    
    Mike Robinson : Definitely the most reliable way, especially when it comes to further manipulation. IE 6/7 don't do innerHTML on tables at all. Also, innertHTML? Is that what Yahoo uses?
  • Inline style tags should be recognized. A styelsheet block will not, as they are loaded at the page's initial render time.

    You can dynamically add classes you the existing stylesheet, but you'll have to parse your HTML fragment to grab what's there and do it in script.

    see: Totally Pwn CSS with Javascript

0 comments:

Post a Comment