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

你离开我真会死。 提交于 2019-12-10 16:15:52

问题


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'/>
<script 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>

回答1:


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).



来源:https://stackoverflow.com/questions/7593913/why-dhtml-behavior-not-work-in-ie8-if-document-write-is-executed-in-head

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!