Skip to content

Instantly share code, notes, and snippets.

@SecretDeveloper
Last active August 29, 2015 14:04
Show Gist options
  • Save SecretDeveloper/a097029da7ebdd4b4a31 to your computer and use it in GitHub Desktop.
Save SecretDeveloper/a097029da7ebdd4b4a31 to your computer and use it in GitHub Desktop.
Safely loading JS libraries (jQuery)
function loadScript(address, callback) {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", address);
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
callback();
}
};
} else { // Other browsers
script_tag.onload = callback;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
function scriptLoadHandler() {
root._myNS.widget = new widget();
root._myNS.widget.render();
console.log('Widget $ is on version: ' + root._myNS.$.fn.jquery);
console.log('Page $ is on version: ' + $.fn.jquery);
}
function load() {
// version of jQuery check
if (!root._myNS.$ || !root._myNS.$.fn || !root._myNS.$.fn.jquery || root._myNS.$.fn.jquery !== '1.11.1') {
//load jquery we need
loadScript('http://code.jquery.com/jquery-1.11.1.min.js', function () {
root._myNS.$ = window.jQuery.noConflict(true); // set our widget library to the newly loaded version
loadScript(urlRoot + 'js/widget.js', scriptLoadHandler);
});
} else {
//skip jquery and just load widget
loadScript(urlRoot + 'js/widget.js', scriptLoadHandler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment