While John Resig's recommendation is, quite rightly, to declare all events within a jquery.document.ready()
function, I know that you don't actually have to put everything in there. In fact, there are cases where it may be more appropriate to deliberately put methods outside of the ready event.
But what are those cases? Obviously best practice dictates that all events are declared within the ready event, so what would best practice be for decl开发者_开发百科arations outside that event?
Edit
Remember, I'm not just after the less-obvious stuff, but I'd like to get a good account of the obvious parts as well. For example, if I'm writing a plugin, I wouldn't encapsulate that code in a jquery.document.ready()
call.
Putting things into the ready
event makes sure that the full DOM is available at the time the function is called.
Any functions and events not depending on the DOM don't need to be put into the ready
event.
Sometimes you even need to keep things out of the ready
function, e.g. document.write()
commands that are supposed to place HTML into the markup at the position the script is at.
Put everything in jquery.document.ready() which:
- changes layout (you want to prevent page-flicker)
- is needed for user-interaction, to make the page usable
What can postponed is:
- everything not important for the user, for example analytics, ads
- things (slightly) improving the user experience
- fetching non-essential widgets or buttons to be added to the page
精彩评论