What event does JQuery $function() fire on?

We have a JQuery $(function() statement as:

<script type="text/javascript">
$(function(){
  //Code..
})
</script>

Dumb question - when exactly is this function executed? Is it when the entire HTML page has been downloaded by the client?

What is benefit of using the wrapping your code within $(function() as opposed to just doing:

<script type="text/javascript">
//Code..
</script>

It is executed as soon as the DOM is parsed and is invoked in order of appearance if there are multiple appearances. At this point the document is however not displayed, its just parsed.


It fires when the document has been parsed and is ready, and is the equivalent of $(document).ready(function () { }) .

The obvious benefit is that having your script tag before other elements on the page means that your script can interact with them even though they're not available at parse time. If you run your script before elements have been parsed and the document is not ready, they will not be available for interaction.


When the document completes loading. It is the same as writing this:

$(document).ready(function(){});

EDIT: To answer your second question:

If you don't wrap your code in the block above then it would fire as soon as it is encountered instead of after all the controls on the page have loaded. So if a block was at the top of a page and it referred to elements in the page those references would not work as the elements have not loaded yet.

But if you wrap in the block then you know that the page has loaded and all elements are available to now reference.

链接地址: http://www.djcxy.com/p/71528.html

上一篇: 一个PHP函数来检查cookie

下一篇: JQuery $ function()激发什么事件?