News for hackers. Stuff that matters.
Re:Don’t let jQuery’s $(document).ready() slow you down by vasi on Thursday August 19, 2010 @07:07PM (#1618970)
Seems to me that AJAX before document-ready could get complicated once you want to actually do something with the response. Normally one would do something like this:

  $(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!

Re:Don’t let jQuery’s $(document).ready() slow you down by Encosia on Thursday August 19, 2010 @07:26PM (#1619018)
The way browsers implement both JavaScript and document rendering via a single-threaded execution queue, that isn't an issue. Once the page begins rendering, callbacks won't have a chance to execute until after the document is rendered and ready. That's the same mechanism that makes the setTimeout(fn, 0) trick work, for example.

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.

Re:Don’t let jQuery’s $(document).ready() slow you down by MBlume on Thursday August 19, 2010 @07:12PM (#1618992)
swap the first two lines:

  $.getJSON(my_url, function(data) {
    $(document).ready(function(){
      $('<p>').text(data.some_text).appendTo('#some_container);
    });
  });
Re:Don’t let jQuery’s $(document).ready() slow you down by photon_off on Thursday August 19, 2010 @07:19PM (#1619012)
Very clever. This works because $(document).ready will execute immediately if the page is already loaded.