3 ms·
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
by vasi 16y ago
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!
- MBlume 16y agoswap the first two lines: $.getJSON(my_url, function(data) { $(document).ready(function(){ $('<p>').text(data.some_text).appendTo('#some_container); }); });
- photon_off 16y agoVery clever. This works because $(document).ready will execute immediately if the page is already loaded.
- deleted 16y ago[deleted]
- Encosia 16y agoThe 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.