Often we have pages and master pages and "bundles" that load scripts like jQuery and we can't always be sure that a particular page already has it loaded. Here is a script that will only inject jQuery into a page if it has not already been loaded:
<HTML>
<HEAD>
<!-- comment or uncomment next line to test it out --->
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script>
// Only do anything if jQuery isn't defined
if (typeof jQuery == 'undefined') {
function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
// callback function provided as param
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
};
};
head.appendChild(script);
};
getScript('https://code.jquery.com/jquery-3.1.0.min.js', function() {
if (typeof jQuery=='undefined') {
// Super failsafe
} else {
alert("We Loaded it!");
// jQuery loaded
}
});
} else {
// jQuery was already loaded
alert("jQuery is Already Loaded!");
// Run your jQuery Code
};
</script>
</HEAD>
<BODY>
</BODY>
</HTML>