Async and document ready











up vote
31
down vote

favorite
12












I try to optimize my pages by putting some async attributes on my scripts. It seems to break my javascript since $(document).ready is executed before the all scripts are loaded!



I saw that I can resolve my problem by putting $(window).load instead of $(document).ready but I was wondering if there is a better solution.
This solution trigger 2 problems in my case :




  1. I have to change all $(document).ready and tell all the developpers to not use it anymore

  2. The scripts will be executed after all images are loaded. My website has a lot of heavy images and I really need some scripts to be executed ASAP after dom is ready.


Do you have some magic tricks? Maybe putting all scripts at the end? use defer instead of async?










share|improve this question






















  • document ready calls are executed also for scripts using document.ready after jQuery detected the document ready state. On a site where jQuery is used, try to use the following after all resources are loaded: $(document).ready(function () {console.log('READY');});
    – thet
    Dec 12 at 6:58

















up vote
31
down vote

favorite
12












I try to optimize my pages by putting some async attributes on my scripts. It seems to break my javascript since $(document).ready is executed before the all scripts are loaded!



I saw that I can resolve my problem by putting $(window).load instead of $(document).ready but I was wondering if there is a better solution.
This solution trigger 2 problems in my case :




  1. I have to change all $(document).ready and tell all the developpers to not use it anymore

  2. The scripts will be executed after all images are loaded. My website has a lot of heavy images and I really need some scripts to be executed ASAP after dom is ready.


Do you have some magic tricks? Maybe putting all scripts at the end? use defer instead of async?










share|improve this question






















  • document ready calls are executed also for scripts using document.ready after jQuery detected the document ready state. On a site where jQuery is used, try to use the following after all resources are loaded: $(document).ready(function () {console.log('READY');});
    – thet
    Dec 12 at 6:58















up vote
31
down vote

favorite
12









up vote
31
down vote

favorite
12






12





I try to optimize my pages by putting some async attributes on my scripts. It seems to break my javascript since $(document).ready is executed before the all scripts are loaded!



I saw that I can resolve my problem by putting $(window).load instead of $(document).ready but I was wondering if there is a better solution.
This solution trigger 2 problems in my case :




  1. I have to change all $(document).ready and tell all the developpers to not use it anymore

  2. The scripts will be executed after all images are loaded. My website has a lot of heavy images and I really need some scripts to be executed ASAP after dom is ready.


Do you have some magic tricks? Maybe putting all scripts at the end? use defer instead of async?










share|improve this question













I try to optimize my pages by putting some async attributes on my scripts. It seems to break my javascript since $(document).ready is executed before the all scripts are loaded!



I saw that I can resolve my problem by putting $(window).load instead of $(document).ready but I was wondering if there is a better solution.
This solution trigger 2 problems in my case :




  1. I have to change all $(document).ready and tell all the developpers to not use it anymore

  2. The scripts will be executed after all images are loaded. My website has a lot of heavy images and I really need some scripts to be executed ASAP after dom is ready.


Do you have some magic tricks? Maybe putting all scripts at the end? use defer instead of async?







jquery html html5






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 15 '12 at 1:46









tibo

3,59832544




3,59832544












  • document ready calls are executed also for scripts using document.ready after jQuery detected the document ready state. On a site where jQuery is used, try to use the following after all resources are loaded: $(document).ready(function () {console.log('READY');});
    – thet
    Dec 12 at 6:58




















  • document ready calls are executed also for scripts using document.ready after jQuery detected the document ready state. On a site where jQuery is used, try to use the following after all resources are loaded: $(document).ready(function () {console.log('READY');});
    – thet
    Dec 12 at 6:58


















document ready calls are executed also for scripts using document.ready after jQuery detected the document ready state. On a site where jQuery is used, try to use the following after all resources are loaded: $(document).ready(function () {console.log('READY');});
– thet
Dec 12 at 6:58






document ready calls are executed also for scripts using document.ready after jQuery detected the document ready state. On a site where jQuery is used, try to use the following after all resources are loaded: $(document).ready(function () {console.log('READY');});
– thet
Dec 12 at 6:58














2 Answers
2






active

oldest

votes

















up vote
27
down vote



accepted










After some extensive research, I can definitely say that putting scripts at the end of the page is THE best practice.



Yahoo agrees with me : http://developer.yahoo.com/performance/rules.html#js_bottom



Google don't talk about this practice and seems to prefer async scripts : https://developers.google.com/speed/docs/best-practices/rtt#PreferAsyncResources



IMHO, putting script at the end of the page has several benefits over async/defer:




  • It will work for all browser (yes, even IE ;) )

  • You guarantee the execution order

  • You do not need to use $(document).ready or $(window).load

  • Your scripts can execute before your images are loaded

  • As async/defer, your page will be displayed quicker

  • When the DOM trigger the ready event, all scripts are loaded

  • Can be optimized by merging all js in one file without problem (by a tool like mod_pagespeed)


The only drawback that I can see is that the browser won't be able to parallelize the downloads.
One good reason to use async/defer instead is when you have a script that is completly independant ( do not need to rely on the execution order) and that don't need to be executed at a specific timing. Example : google analytics.






share|improve this answer





















  • It does not fully guarantee the execution by putting them down in the DOM. If you got too much JavaScript and / or HTML for the browser, you need requirejs or any other system loader like that. I saw design that worked only with compressed JavaScript, because it was too much. It was an bootstrap 3.x respsonsive theme with effects while scrolling down the page.
    – alpham8
    Jun 20 '17 at 6:14




















up vote
0
down vote













If you didn't want to use a script loader, you could use the following approach which would allow you to leave your $(document).ready scripts in place - modified as follows:



$(()=>{

function checkAllDownloads() {
// Ensure your namespace exists.
window.mynamespace = window.mynamespace || {};

// Have each of your scripts setup a variable in your namespace when the download has completed.
// That way you can set async on all your scripts except jquery.
// Use the document ready event - this code - to check if all your scripts have downloaded.
if (window.mynamespace.script1 && window.mynamespace.script2){

// Proceed with page initialisation now that all scripts have been downloaded.
// [ Add your page initialisation code here ].
return;
}
// Not all downloads have completed.
// Schedule another check to give the async downloads time to complete.
setTimeout(checkAllDownloads, 500);
}

// check if it is safe to initialise the page by checking if all downloads have completed.
checkAllDownloads();

})





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11043656%2fasync-and-document-ready%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    27
    down vote



    accepted










    After some extensive research, I can definitely say that putting scripts at the end of the page is THE best practice.



    Yahoo agrees with me : http://developer.yahoo.com/performance/rules.html#js_bottom



    Google don't talk about this practice and seems to prefer async scripts : https://developers.google.com/speed/docs/best-practices/rtt#PreferAsyncResources



    IMHO, putting script at the end of the page has several benefits over async/defer:




    • It will work for all browser (yes, even IE ;) )

    • You guarantee the execution order

    • You do not need to use $(document).ready or $(window).load

    • Your scripts can execute before your images are loaded

    • As async/defer, your page will be displayed quicker

    • When the DOM trigger the ready event, all scripts are loaded

    • Can be optimized by merging all js in one file without problem (by a tool like mod_pagespeed)


    The only drawback that I can see is that the browser won't be able to parallelize the downloads.
    One good reason to use async/defer instead is when you have a script that is completly independant ( do not need to rely on the execution order) and that don't need to be executed at a specific timing. Example : google analytics.






    share|improve this answer





















    • It does not fully guarantee the execution by putting them down in the DOM. If you got too much JavaScript and / or HTML for the browser, you need requirejs or any other system loader like that. I saw design that worked only with compressed JavaScript, because it was too much. It was an bootstrap 3.x respsonsive theme with effects while scrolling down the page.
      – alpham8
      Jun 20 '17 at 6:14

















    up vote
    27
    down vote



    accepted










    After some extensive research, I can definitely say that putting scripts at the end of the page is THE best practice.



    Yahoo agrees with me : http://developer.yahoo.com/performance/rules.html#js_bottom



    Google don't talk about this practice and seems to prefer async scripts : https://developers.google.com/speed/docs/best-practices/rtt#PreferAsyncResources



    IMHO, putting script at the end of the page has several benefits over async/defer:




    • It will work for all browser (yes, even IE ;) )

    • You guarantee the execution order

    • You do not need to use $(document).ready or $(window).load

    • Your scripts can execute before your images are loaded

    • As async/defer, your page will be displayed quicker

    • When the DOM trigger the ready event, all scripts are loaded

    • Can be optimized by merging all js in one file without problem (by a tool like mod_pagespeed)


    The only drawback that I can see is that the browser won't be able to parallelize the downloads.
    One good reason to use async/defer instead is when you have a script that is completly independant ( do not need to rely on the execution order) and that don't need to be executed at a specific timing. Example : google analytics.






    share|improve this answer





















    • It does not fully guarantee the execution by putting them down in the DOM. If you got too much JavaScript and / or HTML for the browser, you need requirejs or any other system loader like that. I saw design that worked only with compressed JavaScript, because it was too much. It was an bootstrap 3.x respsonsive theme with effects while scrolling down the page.
      – alpham8
      Jun 20 '17 at 6:14















    up vote
    27
    down vote



    accepted







    up vote
    27
    down vote



    accepted






    After some extensive research, I can definitely say that putting scripts at the end of the page is THE best practice.



    Yahoo agrees with me : http://developer.yahoo.com/performance/rules.html#js_bottom



    Google don't talk about this practice and seems to prefer async scripts : https://developers.google.com/speed/docs/best-practices/rtt#PreferAsyncResources



    IMHO, putting script at the end of the page has several benefits over async/defer:




    • It will work for all browser (yes, even IE ;) )

    • You guarantee the execution order

    • You do not need to use $(document).ready or $(window).load

    • Your scripts can execute before your images are loaded

    • As async/defer, your page will be displayed quicker

    • When the DOM trigger the ready event, all scripts are loaded

    • Can be optimized by merging all js in one file without problem (by a tool like mod_pagespeed)


    The only drawback that I can see is that the browser won't be able to parallelize the downloads.
    One good reason to use async/defer instead is when you have a script that is completly independant ( do not need to rely on the execution order) and that don't need to be executed at a specific timing. Example : google analytics.






    share|improve this answer












    After some extensive research, I can definitely say that putting scripts at the end of the page is THE best practice.



    Yahoo agrees with me : http://developer.yahoo.com/performance/rules.html#js_bottom



    Google don't talk about this practice and seems to prefer async scripts : https://developers.google.com/speed/docs/best-practices/rtt#PreferAsyncResources



    IMHO, putting script at the end of the page has several benefits over async/defer:




    • It will work for all browser (yes, even IE ;) )

    • You guarantee the execution order

    • You do not need to use $(document).ready or $(window).load

    • Your scripts can execute before your images are loaded

    • As async/defer, your page will be displayed quicker

    • When the DOM trigger the ready event, all scripts are loaded

    • Can be optimized by merging all js in one file without problem (by a tool like mod_pagespeed)


    The only drawback that I can see is that the browser won't be able to parallelize the downloads.
    One good reason to use async/defer instead is when you have a script that is completly independant ( do not need to rely on the execution order) and that don't need to be executed at a specific timing. Example : google analytics.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jun 15 '12 at 11:20









    tibo

    3,59832544




    3,59832544












    • It does not fully guarantee the execution by putting them down in the DOM. If you got too much JavaScript and / or HTML for the browser, you need requirejs or any other system loader like that. I saw design that worked only with compressed JavaScript, because it was too much. It was an bootstrap 3.x respsonsive theme with effects while scrolling down the page.
      – alpham8
      Jun 20 '17 at 6:14




















    • It does not fully guarantee the execution by putting them down in the DOM. If you got too much JavaScript and / or HTML for the browser, you need requirejs or any other system loader like that. I saw design that worked only with compressed JavaScript, because it was too much. It was an bootstrap 3.x respsonsive theme with effects while scrolling down the page.
      – alpham8
      Jun 20 '17 at 6:14


















    It does not fully guarantee the execution by putting them down in the DOM. If you got too much JavaScript and / or HTML for the browser, you need requirejs or any other system loader like that. I saw design that worked only with compressed JavaScript, because it was too much. It was an bootstrap 3.x respsonsive theme with effects while scrolling down the page.
    – alpham8
    Jun 20 '17 at 6:14






    It does not fully guarantee the execution by putting them down in the DOM. If you got too much JavaScript and / or HTML for the browser, you need requirejs or any other system loader like that. I saw design that worked only with compressed JavaScript, because it was too much. It was an bootstrap 3.x respsonsive theme with effects while scrolling down the page.
    – alpham8
    Jun 20 '17 at 6:14














    up vote
    0
    down vote













    If you didn't want to use a script loader, you could use the following approach which would allow you to leave your $(document).ready scripts in place - modified as follows:



    $(()=>{

    function checkAllDownloads() {
    // Ensure your namespace exists.
    window.mynamespace = window.mynamespace || {};

    // Have each of your scripts setup a variable in your namespace when the download has completed.
    // That way you can set async on all your scripts except jquery.
    // Use the document ready event - this code - to check if all your scripts have downloaded.
    if (window.mynamespace.script1 && window.mynamespace.script2){

    // Proceed with page initialisation now that all scripts have been downloaded.
    // [ Add your page initialisation code here ].
    return;
    }
    // Not all downloads have completed.
    // Schedule another check to give the async downloads time to complete.
    setTimeout(checkAllDownloads, 500);
    }

    // check if it is safe to initialise the page by checking if all downloads have completed.
    checkAllDownloads();

    })





    share|improve this answer

























      up vote
      0
      down vote













      If you didn't want to use a script loader, you could use the following approach which would allow you to leave your $(document).ready scripts in place - modified as follows:



      $(()=>{

      function checkAllDownloads() {
      // Ensure your namespace exists.
      window.mynamespace = window.mynamespace || {};

      // Have each of your scripts setup a variable in your namespace when the download has completed.
      // That way you can set async on all your scripts except jquery.
      // Use the document ready event - this code - to check if all your scripts have downloaded.
      if (window.mynamespace.script1 && window.mynamespace.script2){

      // Proceed with page initialisation now that all scripts have been downloaded.
      // [ Add your page initialisation code here ].
      return;
      }
      // Not all downloads have completed.
      // Schedule another check to give the async downloads time to complete.
      setTimeout(checkAllDownloads, 500);
      }

      // check if it is safe to initialise the page by checking if all downloads have completed.
      checkAllDownloads();

      })





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        If you didn't want to use a script loader, you could use the following approach which would allow you to leave your $(document).ready scripts in place - modified as follows:



        $(()=>{

        function checkAllDownloads() {
        // Ensure your namespace exists.
        window.mynamespace = window.mynamespace || {};

        // Have each of your scripts setup a variable in your namespace when the download has completed.
        // That way you can set async on all your scripts except jquery.
        // Use the document ready event - this code - to check if all your scripts have downloaded.
        if (window.mynamespace.script1 && window.mynamespace.script2){

        // Proceed with page initialisation now that all scripts have been downloaded.
        // [ Add your page initialisation code here ].
        return;
        }
        // Not all downloads have completed.
        // Schedule another check to give the async downloads time to complete.
        setTimeout(checkAllDownloads, 500);
        }

        // check if it is safe to initialise the page by checking if all downloads have completed.
        checkAllDownloads();

        })





        share|improve this answer












        If you didn't want to use a script loader, you could use the following approach which would allow you to leave your $(document).ready scripts in place - modified as follows:



        $(()=>{

        function checkAllDownloads() {
        // Ensure your namespace exists.
        window.mynamespace = window.mynamespace || {};

        // Have each of your scripts setup a variable in your namespace when the download has completed.
        // That way you can set async on all your scripts except jquery.
        // Use the document ready event - this code - to check if all your scripts have downloaded.
        if (window.mynamespace.script1 && window.mynamespace.script2){

        // Proceed with page initialisation now that all scripts have been downloaded.
        // [ Add your page initialisation code here ].
        return;
        }
        // Not all downloads have completed.
        // Schedule another check to give the async downloads time to complete.
        setTimeout(checkAllDownloads, 500);
        }

        // check if it is safe to initialise the page by checking if all downloads have completed.
        checkAllDownloads();

        })






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 at 9:14









        john blair

        248




        248






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f11043656%2fasync-and-document-ready%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine