Ajax requests ASAP right before </body>, or on document ready too?

ajax, javascript, jquery, optimization

Solution

Best practice here is to start the Ajax request as soon as possible, but start modifying the DOM only when the document is ready (DOMContentLoaded). To do that, you might use jQuerys Deferred objects which are wired up with jQuerys extended jXHR objects.

<script>
    var req      = $.ajax({}),
        docReady = jQuery.Deferred();

    $(function() {
        docReady.resolve();
    });

    $.when( req, docReady ).done(function( data ) {
        // read the returned data and modify the DOM
    });
</script>

It would be a waste of time to wait for starting the request until the DOM is ready. The XHR request has no business and interest in whats going on with the DOM.

It just makes more sense to decouple those two things entirely. If for some reason the DOM needs a very long time before its ready, you didn't waste the time to let the HTTP request run and collect its data. The other way around, if the request is very slow, you would waste time aswell. So your current snippets are like

DOM ready    
           -> XHR request    
                          -> Do something useful

Whereas my example is like

DOM ready    
XHR request
            -> Do something useful as soon as the DOM and request are ready

Problem

I'm optimizing a page, but I can't tell the difference in results between these (the first one is obviously faster, but I'm not sure if it slows the rendering of the page a little or something): This one will start the request ASAP, and modify the DOM on document ready: ``` <script> $.ajax({ url: '/some-url', success: function() { $(document).ready(function() { // do something }); } }); </script> </body> ``` This one will start the request on document ready: ``` <script> $(document).ready(function() { $.ajax({ url: '/some-url', success: function() { // do something } }); }); </script> </body> ``` Which one is recommended?

Original source