José Romero
José Romero

Reputation: 124

Executing jQuery code after loading jQuery via javascript

I want to load jQuery from Google's CDN, and execute jQuery code if the request succeeded, but I can't seem to get it working right. Here's my code:

function loadjQuery(success, error) {
    var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
    xhr.onload = function() { success(xhr.status, xhr.readyState); }
    xhr.onerror = function() { error(); }
    xhr.open("GET", "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", true);
    xhr.send();
}
loadjQuery(
    function(status, state) {
        console.log(status) // 200
        console.log(state) // 4
        console.log($('body')) // Uncaught ReferenceError: $ is not defined
    },
    function() { setTimeout(loadjQuery, 10000); }
);

Any help would be really appreciated

Upvotes: 0

Views: 197

Answers (2)

Joe W
Joe W

Reputation: 2891

Consider using something like RequireJs ( http://requirejs.org/). You need a modular system to fetch your google source and load it so it is available. You'll then be able to execute actions after the module is loaded. It would potentially be a lot of work to build this yourself as you've started doing.

More on AMD and requirejs can be found in the answer to this question: When does a dynamically loaded JavaScript library become available?

Upvotes: 0

Akshat
Akshat

Reputation: 479

Use the following code to load JQuery

(function () {

function loadScript(url, callback) {

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState) { //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function () {
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

loadScript("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", function () {

     //jQuery loaded
     console.log('jquery loaded');
  console.log($('body') //works


});


})();

Upvotes: 2

Related Questions