3

I am in a situation where I have multiple ASCX files that are being added to an aspx page. Some of these files include the jQuery library. Depending on which ones are added the jQuery library may be included more than once.

I cannot add jQuery at the masterpage or some other level, it must be from the ASCX. The reasons for this are beyond the scope of this question, but if someone really wants an explanation I can provide one.

Is it bad to have jQuery added multiple times in an ASPX page? Is there a way to conditionally add a script to an ASCX page?

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486

2 Answers2

8

in your ascxs you can do

if (typeof jQuery == 'undefined') {   
   // load jquery 
   var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "path/to/jQuery";
    document.getElementsByTagName('head')[0].appendChild(script);
} else {
  //already loaded
}

ref: check if jquery has been loaded, then load it if false

Community
  • 1
  • 1
Rafay
  • 30,950
  • 5
  • 68
  • 101
7

You should not add jQuery more than once.

You can add it conditionally though:

<script>window.jQuery || document.write('<script src="js/jquery-1.8.2.min.js">\x3C/script>')</script>

This is how they to it in the html5boilerplate

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292