Every time you have gone between Microsoft Internet Explorer and other web browsers, that would be completely painful. IE always acts different than others and kicks your ass. And the fact is even different IE versions act different, too. It would drive you crazy.
Here is one I just met again:
<html> <body> <div> <script type="text/javascript"> var p = document.createElement('p'); p.appendChild(document.createTextNode('Hello World!')); document.body.appendChild(p); </script> </div> </body> </html>
This screenshot was taken from IE6 with WINE. If you are using IE7, that would be “blah blah blah. Operation aborted.” This happens on IE 5.5 to IE7. The cause is that you do not wait for DOM gets ready.
Contents
1 Solutions
1.1 The easiest one
Add defer="defer" attribute to your script element. That looks like:
<script type="text/javascript" defer="defer">
1.2 Usually useless solution
Microsoft has noted this bug, yes, they already called a bug. Why this is useless usually? Because we may not have fully control power on the HTML. Besides, move or create new element in existing HTML layout would break out plan of the HTML page.
Consider this scenario: You are a Blogger.com widget developer and your widget uses JavaScript. You ask widget adopter to add a HTML/JavaScript gadget with your code. For minimizing the difficulty of installation, you would not want the adopter to touch template, because not everyone is capable to edit template easily.
1.3 Binding onload event
I personally would recommend this solution. It’s the most elegant way to resolve this issue. You better to chain onload event, unless you pretty sure you are the only one who bind onload. The script may look like:
function ChainLoadEvent(f) { var old_onload = window.onload; window.onload = (old_onload == undefined) ? f : function() { old_onload(); f(); } } ChainLoadEvent(function() { var p = document.createElement('p'); p.appendChild(document.createTextNode('Hello World!')); document.body.appendChild(p); });
Why chaining? Because “you don’t want to the rainforest to die1, do you?” (Fast forward to 4:45)
1.4 Library way
If you are using a JavaScript library, they may already provide their own method, e.g. jQuery’s ready.
2 Further reading
You can search on Google for related entries.
[1] | http://www.youtube.com/watch?v=rcyAOvZ0LpQ is gone. It’s a clip from The IT Crowd. |
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.