Neha Jain Neha Jain - 2 months ago 13
Javascript Question

Getting "$ is undefined" error after changing jQuery script loading to async

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>

Answer

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>