Search code examples
jquerydeferred-loading

Can't Use Async defer with Jquery Script


I'm trying to use async defer with this script but it affects the functionality. I'm not sure what I'm doing wrong? If you need to see the website, Here's the info: The Hangout

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
    $(window).bind("load", function() {
      $(window).scroll(function () {
          if ($(this).scrollTop() > 600) {
              $('.scrollup').fadeIn();
          } else {
              $('.scrollup').fadeOut();
          }
      });
      $('.scrollup').click(function () {
          $("html, body").animate({
              scrollTop: 0
          }, 600);
          return false;
      });
      });
        </script>

Solution

  • With defer your scripts are loaded in the order they are specified, but not before the document itself has been loaded (including inline code).

    You can do one of two things:

    1. Move your inline code to an external file while using defer
    2. Wrap your inline code in a DOMContentLoaded event callback

    And the callback would look like:

    window.addEventListener('DOMContentLoaded', function() {
      $(window).scroll(function () {
        $('.scrollup')[$(window).scrollTop() > 600 ? 'fadeIn' : 'fadeOut']();
      });
      $('.scrollup').click(function () {
        $("html, body").animate({scrollTop: 0}, 600);
        return false;
      });
    });