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

Categories

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

javascript - jQuery document.ready vs self calling anonymous function

What is the difference between these two.

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

  2. (function(){ ... })();

Are these both functions called at the same time? I know, document.ready will be triggered when the entire HTML page is rendered by the browser but what about 2nd function (self calling anonymous function). Does it wait for browser to complete rendering the page or it is called whenever it is encountered?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)
  • $(document).ready(function(){ ... }); or short $(function(){...});

    This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.

  • (function(){ ... })();

    That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefor, its very unlikely that you can successfully act on DOM elements here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...