1

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?

arxoft
  • 1,070
  • 1
  • 12
  • 27

2 Answers2

1

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');

    });


})();
Mihai Matei
  • 22,929
  • 3
  • 29
  • 46
0

you need to add listener for

 script.onload = myCallback;

event and trigger jQuery functions only then

shershen
  • 9,496
  • 10
  • 36
  • 55