Search code examples
jqueryxmlhttprequest

Dynamically referencing JQuery using XmlHttpRequest object


I am trying to load jQuery using xmlhttrequest object

I have following code:

 loadDoc("https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js", myFunction1);

    function loadDoc(url, cFunction) {
      var xhttp;
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          cFunction(this);
        }
      };
      xhttp.open("GET", url, true);
      xhttp.send();
    }

    function myFunction1(xhttp) {
      // action goes here
      $(document).ready(function() {
        alert('test');    
    });

    } 

I am getting the error:

(index):62 Uncaught ReferenceError: $ is not defined
    at myFunction1 ((index):62)
    at XMLHttpRequest.xhttp.onreadystatechange ((index):53)
    at loadDoc ((index):57)
    at window.onload ((index):46)

Any reason why this is happening?

I typically want to do it this way as I won't be able to use as I am within a CRM form.


Solution

  • Try to run this script on the console here and you will see that your code is excuted without problem. The problem with your code is that you are tring to use the $ sign of Jquery in this line

    $(document).ready(function() {

    but you are not realy initilize the Jquery library on the page so javascript does not recognize this sign.

    If you want to include the Jquery library inside the page you should do it likt in this question - include jquery