Monday, January 21, 2008

Javascript: Error, Internet Explorer cannot open the internet site

I have built a website that used a lot of javascript code to generate a floating overlay div, appends it to the body, and got this crazy Internet Explorer error in IE 6 AND IE 7.

Internet Explorer cannot open the internet site http://blah.blah.com/

Operation Aborted.


At which point I got redirected to a "The page cannot be displayed" IE error.

I trimmed everything out of the webpage which had nothing to do with the error and I was left with a tiny page which still produced the error:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
<
head>
<
meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<
title>pagetitle</title>
<
script language="JavaScript" type="text/JavaScript">
<!--
function creatediv()
{
try
{
document.body.appendChild( document.createElement("<div>") );//IE
}
catch (e)
{
document.body.appendChild( document.createElement("div") );
}
}
//-->
<
/script>
<
/head>
<
body>

<
div>
<
script language="JavaScript" type="text/JavaScript">
<!--
creatediv();
//-->
<
/script>
<
/div>

<
/body>
<
/html>


If you copy and paste the above, and then save it as html, and open the page in IE you will see the error. Then I googled around and played with my page, and realized that if I moved the creatediv() function outside the >div< (or any other html container), that I would no longer get this error. Basically, the problem is that IE 6 and 7 do not create the document.body part of the DOM until after the page has finished loading. In my javascript code I call document.body.appendChild and IE has a hissy fit. Something about calling the javascript from within a div or table makes also contributes to this error.

Workarounds and Solutions:
- moving my javascript function out of the div (see below)
- using <body onload='creatediv()' > instead of calling it within the page
- if using an event handler class like in http://www.dustindiaz.com/rock-solid-addevent/
use: addEvent(window,'load',creatediv);

Code that doesn't produce the error:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html>
<
head>
<
meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<
title>pagetitle</title>
<
script language="JavaScript" type="text/JavaScript">
<!--
function creatediv()
{
try
{
document.body.appendChild( document.createElement("<div>") );//IE
}
catch (e)
{
document.body.appendChild( document.createElement("div") );
}
}
//-->
<
/script>
<
/head>
<
body>

<
div>
<
/div>

<
script language="JavaScript" type="text/JavaScript">
<!--
creatediv();
//-->
<
/script>


<
/body>
<
/html>


source(s): http://tinyurl.com/hvfsw

2 comments:

Ericlaw said...

http://support.microsoft.com/kb/927917/en-us

the pointly newspaper said...

Can u help me with my blog?????

I tried to follow your instructions, but it doesnt work....
Sorry.

Pls pm me at erbinhao@hotmail.com

THANKS