user1547174 user1547174 - 6 months ago 16
Javascript Question

jQuery is not a function in anonymous function

I am trying to write an anonymous javascript function that dynamically loads jquery and angular. However, when I run the function I keep getting 'jQuery is not a function'. Can someone help? Here is my code:

(function() {

var jQuery;
var jquery_tag = document.createElement('script');
var angular_tag = document.createElement('script');

jquery_tag.setAttribute("type", "text/javascript");
jquery_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js");

angular_tag.setAttribute("type", "text/javascript");
angular_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js");

jquery_tag.onload = scriptLoadHandler;
angular_tag.onload = scriptLoadHandler;

(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(jquery_tag);
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(angular_tag);


function scriptLoadHandler() {
jQuery = window.jQuery
main();
}

function main() {
jQuery(document).ready(function($) {
alert('yo'); //this runs
});
}

})();


Here is my fiddle:

https://jsfiddle.net/p7jcofx1/4/

Thanks in advance!

Answer

scriptLoadHandler() will run two times based on this code:

jquery_tag.onload = scriptLoadHandler;
angular_tag.onload = scriptLoadHandler;

Even though the Angular code is listed after the jQuery code, it could load first, making window.jQuery undefined in scriptLoadHandler, and causing jQuery(document) to fail in main().

You can prevent this by updating scriptLoadHandler as follows:

function scriptLoadHandler() {
  if(window.jQuery) {
    jQuery = window.jQuery
    main();
  }
}
Comments