开发者

A couple of questions regarding jQuery's $(document).ready and its use

开发者 https://www.devze.com 2023-04-09 21:26 出处:网络
I have been writing some basic Javascripts, and I am finally giving in to try to learn jquery (less than 24hrs).I am having a problem with understanding syntax with simple lessons/codes that I am twea

I have been writing some basic Javascripts, and I am finally giving in to try to learn jquery (less than 24hrs). I am having a problem with understanding syntax with simple lessons/codes that I am tweaking for my purpose.

Does everything has to开发者_JS百科 be wrapped inside a separate $(document).ready(function())?

Or just have 1 $(document).ready(function()) statement and stuff everything inside of it? Including custom functions.

What happens when you put one inside another?

Sorry for simple question, but the examples online or in my book has the declaration wrapped around the executing code.


Generally, you just have one ready function that will kick off your entire page's event listeners, and initialize any objects that need setting up or what have you.

Here is a very simple page I put together a while ago that has some photo galleries and other 'complex' behaviors, but you can see that it's all stored in one big Page object that only gets inited during the document ready event:

http://threeaprons.com/ta.js

So what I've done is made a large "singleton" that is very page specific, and not reusable anywhere else (IE another site or what have you). This encapsulates the entire site's behavior, and only needs to be inited when the DOM is ready for event listeners, etc.


$(document).ready(function()) has one purpose.

That purpose is to delay execution of the code inside of it until the page is fully loaded and then run it as soon as the page reaches that state. Only initialization code that expects to examine/modify the initial state of the page (and thus has to wait for it to be loaded before examining it) needs to be inside that function.

Other pieces of code that run or get called at a later time do not have to be inside a document.ready block.

You may have one or multiple document.ready blocks - that's really up to how you want to organize your code. If all my code is in support of one app and is in very few set of files, I may just have one document.ready block and put any initialization code in that block. If I have independent modules that I want to be able to stand alone and easily be used in other projects, then I may use a separate document.ready block for each module just to make the organization of the code more independent.

There is no right or wrong way to do it - it just depends upon how you want/need to organize your code.

0

精彩评论

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

关注公众号