开发者

Necessity of .ready() in jQuery

I've seen various examples use this and I'm curious to know, is it dangerous not to wrap jQuery code in the following?

$(document).ready(function () {});
开发者_如何学运维

I know what it does and I know why you do it but I'm curious if it is more unsafe or just bad practice/style to not have it? Thanks!


You use it if your code needs to access the DOM.

If you're just setting up classes and modules, but not actually running them, then you don't need to wrap them in the ready handler.

However, if you're doing something that requires elements to be loaded (like, adding event handlers) then you need to do it in the ready() event.

EDIT:

Here is an example: http://jsfiddle.net/ctrlfrk/43n8U/ Try commenting out the addHandler functions and see what happens.

(Note that I've set jsfiddle to run this code in the head tag, by default it usually places the code in the onload event, which negates the need for the ready handler)


It depends on where you are placing your scripts. If you add a script tag just before the closing <body> you don't need to use it because the DOM will already be loaded. On the other hand if you place your script tag inside the <head> section and access the DOM you absolutely need to use it or your script won't work because at the moment your script executes the browser hasn't yet read and parsed the DOM.


See this (already answered)

jQuery ready function aliases

for those that the above is tl;dr; :

Additional reading: http://api.jquery.com/ready/


Wrapping your code in ready() function only delays the running of that code until the page has been loaded. The code does not get "safer" somehow.

But many times you want to run some code that will query the DOM that is created after the script-tag that your code is in, or simply need some structures from the document that are placed after that script tag. If that is the case, then ready() is for you.

But generally there is no valid reason not to use ready() function, so that's why everybode almost always use it.


I think you should also be aware of jQuery's $(window).load() and how it differs from $(document).ready()

Read more about it here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜