Skip to content

Instantly share code, notes, and snippets.

@jenyayel
Created November 19, 2017 20:32
Show Gist options
  • Save jenyayel/d676554930c7a02904eb62188ad5a4d7 to your computer and use it in GitHub Desktop.
Save jenyayel/d676554930c7a02904eb62188ad5a4d7 to your computer and use it in GitHub Desktop.
jQuery async loader to page
function ensureJquery(readyCallback) {
if (window.jQuery === undefined || parseFloat(window.jQuery.fn.jquery) < 1.9) {
var js = document.createElement('script');
js.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js";
if (js.readyState)
js.onreadystatechange = function () {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
jQueryLoadHandler();
}
};
else
js.onload = jQueryLoadHandler;
(document.getElementsByTagName('head')[0] || document.documentElement).appendChild(js);
} else {
readyCallback(window.jQuery);
}
function jQueryLoadHandler() {
readyCallback(window.jQuery.noConflict(true));
}
}
@jenyayel
Copy link
Author

@khaliullin, just noticed your comment. You call the method ensureJquery and provide callback, which will be called after:

  • In case there is already loaded jQuery on page with version 1.9 or higher (you can change the version number)
  • In case there is no jQuery on page at all, or it is lower than 1.9, then the method will load and inject it into page without conflicting with the version presented on the page

The callback that you specify will get an argument, which will be jQuery object in version 1.9 or higher without changing window global object jQuery.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment