Google+ Peter Bromberg's .NET Blog | How to Ensure that jQuery is only loaded once

Peter Bromberg's .NET Blog All Things Programming

How to Ensure that jQuery is only loaded once

26. July 2016 13:50 by admin in ASP.NET, C#, Jquery

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:


<!-- comment or uncomment next line to test it out --->
<script src=''></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


script.onload = script.onreadystatechange = null;







getScript('', 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









Add comment

  Country flag