views:

104

answers:

3

This might be more of a philosophical debate, but here is what I have:

  • Two controls which share a Javascript resource library to call a webservice.
  • They are ususally used in conjunction with each other, but not always.
  • The javacsript file they both reference is not easily separated.
  • The javascript file should not be added to every page in the application.

Ideally I would divide the webservice between the controls and have each call a js resource file targeted just to the functionally they need.

I'm wondering if there is an obvious better way that I'm missing...

In its simplest form I have:

<html> 
<head>
</head>
<div>
    <h1>Control1</h1>
    <script type="text/javascript" src="/Webservice.asmx/js"></script>
</div>
<div>
    <h1>Other stuff</h1>
</div>
<div>
    <h1>Control2</h1>
    <script type="text/javascript" src="/Webservice.asmx/js"></script>
</div>
</body>
</html>

Edit
I have jQuery available to me if this provides a helpful method.

Using ASP.NET

+1  A: 

If those controls don't need to share information between them, you could check out jQuery's method of using objects, wich ensures that if you name the main object differently, it would instanciate (not sure if this word exists) 2 variables refeering the same object.

yoda
+1  A: 

Probably easiest approach is to include the whole js resource library once when you are using one or both of the controls. This should be handled by your server side scripting (php etc.)

Store you <script src=".." > tag to head part of the page. When you are adding a new control to the page, check if head part already contains the required library, if not, then add the library. Do not include same libary more than once per page, if at all possible.

For example:

<html> 
  <head>
     <script type="text/javascript" src="/Webservice.asmx/js" />
  </head>
  <body>

    <h1>Control1</h1>

    <h1>Control2</h1>

  </body>
</html>


The optimal, in page load time sense, is to make three versions of the resource library. However this is most likely overkill.

  1. version contains required parts for control A
  2. version contains required parts for control B
  3. version contains all required parts for controls A and B

Then you must select correct version depending if you are using control A, control B or both.

Juha Syrjälä
+1  A: 

Solved my issue with the following JS & jQuery code

if (thisResourceLoaded === undefined) 
{ 
    $.getScript('/Webservice.asmx/js');
    var thisResourceLoaded = true; 
}
Chris Ballance
That'll do it. I was going to suggest `dojo.require` if you weren't using jquery.
Justin Johnson