Don’t let jQuery’s $(document).ready() slow you down
encosia.com
encosia.com
But either way he makes a great point on the document.ready if your page depends on ajax or some sort of ui styling its probably best in the header script.
$(document).ready() can be a bit of a sledgehammer in terms of latency.
Sorry if that wasn't very clear in the article.
$(document).ready(function(){
$.getJSON(my_url, function(data) {
$('<p>').text(data.some_text).appendTo('#some_container);
});
});
But if we call getJSON before document-ready, the node $('#some_container') may not yet exist! Now we need some way to wait until both the AJAX request is complete and the document is ready…recommendations?EDIT: Thanks for the responses, glad to know it's safer than I thought!
It feels a bit like driving fast with no seat belt on, but it's safe.
If you do want to be extra cautious, MBlume's suggestion to wrap the success handler in $(document).ready() works fine too. That's effectively the same as not wrapping it.
$.getJSON(my_url, function(data) {
$(document).ready(function(){
$('<p>').text(data.some_text).appendTo('#some_container);
});
});I prefer
$(function(){});
to
$(document).ready(function(){});
jQuery(document).ready(function(){});
Using $(function(){}); serves as a nice warning to this effect.
jQuery(document).ready(function($){}); (function($, window, undefined) {
$(document).ready({
// etc.
});
}(jQuery, window);
[1] http://www.yuiblog.com/blog/2007/06/12/module-pattern/ $(function () {
$('#index').append($('article p:first-child'));
});
becomes: $ -> $('#index').append $('article p:first-child')
Not exactly noob-friendly, but very concise.jQuery(function($){
});
It would avoid noConflict type problems.
But, regardless, event delegation needs more love, yup.