Skip to content

Instantly share code, notes, and snippets.

@tomviner
Created January 30, 2016 20:59
Show Gist options
  • Save tomviner/b357db95a2e3162a8b36 to your computer and use it in GitHub Desktop.
Save tomviner/b357db95a2e3162a8b36 to your computer and use it in GitHub Desktop.
Add jQuery to a page.
(function() {
var b = document.getElementsByTagName('body')[0];
otherlib = false;
if (typeof jQuery != 'undefined') {
console.log('This page already using jQuery v' + jQuery.fn.jquery);
} else if (typeof $ == 'function') {
otherlib = true;
}
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('//code.jquery.com/jquery-latest.min.js', function() {
if (typeof jQuery == 'undefined') {
console.log('Sorry, but jQuery wasn\'t able to load');
} else {
console.log('This page is now jQuerified with v' + jQuery.fn.jquery);
if (otherlib) {
console.log(' and noConflict(). Use $jq(), not $().');
$jq = jQuery.noConflict();
}
}
console.log('Call your function here.');
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment