arxoft
arxoft

Reputation: 1475

jQuery dynamically included is not working

I am trying to dynamically include jQuery into the <head>. Here's my code:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded 
    var script = document.createElement('script');
    script.src = 'resources/js/jquery.js';
    script.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);
    alert(typeof jQuery);
} 

It works well and I see the <script> tag in <head>; the jquery.js file is also correct and error less. Even then all I get for alert(tyeof jQuery) is undefined. why?

Upvotes: 1

Views: 58

Answers (2)

shershen
shershen

Reputation: 9993

you need to add listener for

 script.onload = myCallback;

event and trigger jQuery functions only then

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

Try adding jQuery and assign a callback after loading it.

See both examples with and without callback here: http://www.sitepoint.com/dynamically-load-jquery-library-javascript/

(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/1.6.1/jquery.min.js", function () {

         //jQuery loaded
         console.log('jquery loaded');

    });


})();

Upvotes: 1

Related Questions