Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm curious what situations exactly require the use of jquery's $(document).ready() or prototype's dom:loaded or any other variant of a handler for this event.

In all the browsers i've tested, it's entirely acceptable to begin interacting with html elements and the DOM immediately after the closing tag. (e.g.

<div id="myID">
 My Div
</div>
<script type="text/javascript">
$('#myID').initializeElement();
</script>

So at this point i'm wondering whether $(document).ready() is merely there to reduce the thinking involved in writing javascript code that runs during page load. In the case of using $(document).ready() there is regularly rendering issues such as popping and 'artifacts' between the browser first starting to draw the page and the javascript actually executing when the page is 'ready'.

Are there any scenarios where $(document).ready() is required?

Are there any reasons I shouldn't be writing initialization scripts as demonstrated?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
174 views
Welcome To Ask or Share your Answers For Others

1 Answer

The main reason is external files that are included in the head. When you include a file in your <head> it gets run immediately. This means if the JavaScript interacts with the DOM it needs to be wrapped in Dom Ready.

It's also needed for unobtrusive JavaScript and separations of concerns. Ideally your JavaScript and HTML are in separate files. If you follow this you will not have any in-line script tags in your HTML at all.

The second is to defend yourself against obscure browser bugs when you make mistakes. There are cases where it's not save to go and manipulate DOM elements immediately afterwards. (I'm looking at you IE6!)

The third reason is to keep your code clean.

Mixing script tags into your HTML makes spaghetti code.

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

some HTML
<script> ... </script>

We have code about ten times worse then that. It's a right pain to read / maintain


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...