问题
What should be in and what should be out of a jQuery.ready() ?
On a performance perspective, I've read somewhere that putting all the codes wrapped inside a jQuery.ready()
isn't an efficient way to go.
Then my question is : what should be in and what can be oustide without problems (I guess delegates could be kept outside but it's a fast guessing) ?
Thank you
回答1:
For ultimate performance put your js before the closing body tag. That way you can eliminate jquery ready altogether. The UI loads fast as it is not blocked by scripts being downloaded and when the js is parsed and invoked you can be sure the elements in the dom above are ready to be manipulated.
回答2:
jQuery.ready() is called after the page is done loading. See first sentence in jQuery.ready(). If you want events to fire before the page is done loading jQuery.ready() would not be the way to go.
回答3:
You should keep function delcarations such as
fnc = function() { ... };
or any other declaration. Because if you shove it all in, that code will start executing only when the whole DOM has loaded. Otherwise, it starts executing as soon as it downloaded. The jQuery wrapper should only be present when your javascript requires the DOM to be downloaded.
var blah = function() {
//...
};
$(function() { //same as jQuery(document).ready or $(document).ready
blah();
});
来源:https://stackoverflow.com/questions/5887971/what-should-be-in-and-what-should-be-out-of-a-jquery-ready