Softalent
Softalent

Reputation: 269

Uncaught ReferenceError: jQuery is not defined even working on console

I need to include jQuery in js file since it would be loaded as a external script.

Here is my code:

function addjQuery() {
  if (!window.jQuery) {
    var jq = document.createElement("script");
    jq.type = "text/javascript";
    jq.src = "https://code.jquery.com/jquery-3.2.1.min.js";
    document.getElementsByTagName("head")[0].appendChild(jq);
    console.log("Added jQuery!");
  } else {
    console.log("jQuery already exists.")
  }
}
addjQuery();

jQuery(function($) {
  $(document).ready(function() {
  });
});

But error occurs: Uncaught ReferenceError: jQuery is not defined

Even when I run "jQuery" or "$" on console of chrome dev tool, it's working.

What's the problem?

Upvotes: 1

Views: 1797

Answers (1)

hackerrdave
hackerrdave

Reputation: 6706

The jQuery() function is firing prior to jQuery being loaded from the script tag - you can add an onload event handler to fire it when the script is done downloading:

function addjQuery() {
  if (!window.jQuery) {
    var jq = document.createElement("script");
    jq.type = "text/javascript";
    jq.src = "https://code.jquery.com/jquery-3.2.1.min.js";
    document.getElementsByTagName("head")[0].appendChild(jq);
    jq.onload = initjQuery;
    console.log("jQuery is loaded!");
  } else {
    console.log("jQuery already exists.")
  }
}

function initjQuery () {
  jQuery(function($) {
    $(document).ready(function() { });
  });
}

addjQuery();

Upvotes: 3

Related Questions