0

I am trying to append jQuery library via JavaScript code like this:

    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'
    document.head.appendChild(script);

if (window.jQuery) {  
    document.write('jQuery is loaded') 
} else {
    document.write('jQuery is not loaded');
}

The above code is not executing the src file and I am not able to find jQuery element. To confirm I have added this piece of code:

if (window.jQuery) {  
    document.write('jQuery is loaded') 
} else {
    document.write('jQuery is not loaded');
}

JsFiddle: https://jsfiddle.net/vyeyhrrL/

The output I am seeing is "jQuery is not loaded".

Can you let me know what I am missing?

Edit:

Thanks to comments, this is working:

    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
script.onload = function(script){
            console.log(script + ' loaded!');
if (window.jQuery) {  
    document.write('jQuery is loaded') 
} else {
    document.write('jQuery is not loaded');
}
        };
    document.head.appendChild(script);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Raghav
  • 8,772
  • 6
  • 82
  • 106

0 Answers0