The D Merged
The D Merged

Reputation: 680

$ not defined, when trying to load jQuery on the fly

Consider this script saved in script.js :

if ((typeof window.jQuery) == "undefined") {
    var js = document.createElement("script");
    var he = document.getElementsByTagName('head')[0];
    js.type = "text/javascript";
    js.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
    he.appendChild(js);
}


$('document').ready(function(){
    alert('testing');
});

Then a basic html page like this:

<html>
    <head>
    </head>
    <body>
    </body>
</html>

<script src=script.js></script>

This result in an error:

ReferenceError: $ is not defined
script.js
Line 8

Why is $ not defined? First comes the code between if, then the code ready(). This queues the code in the callback function to be called when the document is loaded right?

If I look at the code in Firebug, jQuery is properly loaded. Does this happen after document.read ? or is it something else I missed here?

Upvotes: 1

Views: 363

Answers (1)

Brigand
Brigand

Reputation: 86220

If you insist on loading scripts in this way, ask the browser to let you know when it's actually ready to use.

if (typeof jQuery !== "function") {
    var js = document.createElement("script");
    var he = document.getElementsByTagName('head')[0];
    js.type = "text/javascript";
    js.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js";
    he.appendChild(js);

    js.addEventListener("load", function () {
        alert(typeof $);  // function
    });
}

alert(typeof $); // undefined

Side note: it's usually better to strictly check types. If window.jQuery is an object, number, or string, your code shouldn't be okay with that.

Upvotes: 2

Related Questions