开发者

Why DHTML behavior not work in IE8 if document.write is executed in <head>?

We have a 3rd party web application which works on in IE6, but not works in IE8.

The sample code is like below, the "message from .htc" message will popup in IE6, but not popup in IE8.

test.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<sc开发者_运维技巧ript type='text/javascript'>
    //if comment the following line, or move this script in <body>,
    //then HTC will work in IE8
    document.write ("<h1>document.write() in &lt;head&gt;</h1> some calendar codes");
</script>
</head>

<body style='behavior:url(test.htc)'>
HTML Components test
</body>
</html>

test.htc

<script type='text/javascript'>
alert ("message from .htc");
</script>

Why this happened? Any compatible documents to explain this?


Solution

As @Quentin said or another expert from http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/c1f546f6-d7e1-4b46-a1c9-8f02eaf1286b said, IE8 probably make rules strictly compared to IE6, and IE8 may treat it as an corrupt HTML document.

So, I decide to to use document.createElement to create elements dynamically instead of document.write, and insert these elements to DOM after some seconds delay. After some tests, it finally worked both in this test.html and real application.

test-ie8-compatible.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript'>
function Delay_CreateCalendar()
{
    var oContainer = document.createElement ("div");
    var oCalendarIFrame = document.createElement ("iframe");
    oContainer.appendChild (oCalendarIFrame);
    document.body.insertBefore (oContainer);
}
setTimeout (Delay_CreateCalendar, 2000);
</script>
</head>

<body style='behavior:url(test.htc)'>
dhtml HTC 测试
</body>
</html>


Presumably, despite the namespace, you are serving the document as text/html. In HTML the start and end tags for the head and body element are optional. H1 elements are not allowed inside the head.

Thus, when you document.write and H1 inside the end, you trigger the end of the head and the start of the body.

I assume that IE then ignores the start tag for the body element as it would create a second body (which also isn't allowed).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜