Monday, June 18, 2012

Solution: Inline CSS issue and Ajax call with IE6 to IE8



I have an application where I need to display html content by making Ajax call. The html content in html page with inline CSS (<style></style> tag inside html page). I have a <div> element in my main page and I make Ajax request to load the html content and set the content in <div> as innerHTML or using jQuery html(). The html content is displaying perfectly in Firefox 12 and Chrome 19 and also work nicely in IE 9. But when I made a Ajax request using IE 7 or IE 8 the html content is displaying without inline styling in page. The problem is also specified in web and is a known bug of IE They suggest to use CSS in global file. But my each content has different CSS style and that is not part of our application and  content can be changed any time also. So we can not replace inline CSS in another CSS file. I tried to find alternative solution of this problem  where inline CSS can be considered in IE 6 to 8 but It did not work. We also tried to refresh the DOM but failed to display content with inline style.


jQuery has two method for inserting html content inside a <div> or other DOM elements. One is html() and another is append(). html() function of jQuery works same as setting InnerHTML inside DOM element and it replaces the previous content. But append() does not replace existing content and it appends content at the end of existing content. To replace the content empty() method should be called and just after we can call append(). It may look like both are doing same things. But append does not only set the InnerHTML inside DOM element. It do much complicated work. If you watch the append() function inside jQuery.js file you will see it first manipulates the DOM inside the html content. If you see the clean function inside jQuery then you will find it creates JQuery collection from html string. If you write your own code to create JQuery collection and append inside <div> using appendChild that will work with styling in FireFox not in IE also you will get less elements inside JQuery collection. Inside the append() function style problem is fixed but code is much complex to understand which code actually solved the problem. So if you use Jquery empty().append() function instead of html() or innerHTML for IE 6 to IE8 , you can see the content with inline CSS making Ajax call.

The simple solution for IE 6 to IE 8 is

    var url = "inline.html";
url: url,
success: function (html) {

error: function () { return null; }

Here is the demo of the solution.

No comments:

Post a Comment