0

I am getting a "$ is undefined" error on $(document).ready() after changing jQuery script loading to async.

Following is the short version of my code. It was working before I added the async attribute to my <script> tag that loads jQuery.

I did this based on the recommendation provided by Google Page Insight to improve my page's performance

<script src="/scripts/jquery.min.js" async></script>
<script>
    $(document).ready(function(){  
       //Some variable initialization 
    });
</script>
4
  • 6
    Of course you get that, because the first script is not yet loaded when the second one gets executed … that’s what async means. You want defer instead – that does preserve and guarantee execution order. Commented Nov 20, 2015 at 20:31
  • 1
    Use google hosted libraries. Commented Nov 20, 2015 at 20:33
  • But will defer impact page load time in google page insight check. Commented Nov 20, 2015 at 20:36
  • why vote down? i am getting error so ask question Commented Nov 21, 2015 at 8:45

1 Answer 1

3

You can force your initialization code to wait until jQuery is loaded by calling it from an onload handler on your <script> tag:

<script src="//code.jquery.com/jquery-1.11.3.min.js" async onload="init()"></script>

<script>
  function init() {
    $(document).ready(function() {
      //Some variable initialization 

      console.log("loaded");
    });
  }
</script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.