Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - when do you need to use $(document).ready()?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...