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

We have a third-party web application that works in IE6 but does not work in IE8.

Sample code, as shown below, the message "message from.htc" will pop up in IE6 but not pop up 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 did this happen? Any compatible documents to explain this?


Decision

As @Quentin or another expert from http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/c1f546f6-d7e1-4b46-a1c9-8f02eaf1286b said , IE8 probably makes the rules strictly compared to IE6, but IE8 may refer to it as a damaged HTML document.

So, I decided to use document.createElement to dynamically create elements instead of document.write and paste these elements into the DOM after a few seconds of delay . After some tests, he finally worked both in this test.html and in a 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> 
+4
source share
1 answer

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. Elements H1 are not allowed inside the head.

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

I assume that IE will then ignore the start tag for the body element, as it would create a second body (which is also unacceptable).

+4
source

All Articles