Question

Let me explain the situation:

I have a Sharepoint 2010 solution in VS that contains:

  • Some Model classes
  • A LINQ-to-SQL data context
  • A WCF REST service
  • 3 Visual web parts

The web parts calls some methods in the WCF service using jQuery.

Right now, I'm adding the jQuery script from Microsoft Ajax CDN directly in the Visual Web Part markup (.ascx).

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

The thing is that if more than 1 web part is inserted in the same page, that script is being added more than once.

How can I make things so the script is registered only once, no matter how many web parts are inserted in the same page?

Was it helpful?

Solution

you can also use CustomAction for loading jquery in page.

just create new element file and add custom action tab like that

   <CustomAction
   ScriptSrc="~site/_layouts/yourjquerypath/jquery.js"
   Location="ScriptLink"
   Sequence="100"/>

so do not need to add jquery pugin every time in webparts.

OTHER TIPS

You could use an usercontrol witch you load into the "AdditionalPageHead" section. This will allways include your script, wether or not one (or more) of your web parts is on the page. I used this technique for displaying custom ribbons, and you can find the sourcecode at http://swcustomribbon.codeplex.com/

You don't mention whether you are in the sandbox or a full-trust solution.

For full-trust, you should use the ASP.NET facility for registering scripts: ClientScriptManager

If you follow the pattern in the example on that page, the script will get registered only a single time, and downloaded a single time.

The ClientScriptManager is not available in the sandbox. (Last time I tried, it did not throw any errors, it simply does not work.) As an alternative, the CustomAction/ScriptLink approach would be fine.

Like @V_B said, it is better to load jquery as customaction to all pages, another way is to define scripts in your masterpage. But if that doesn't suit you, you can add jQuery in your webparts conditionally if the script has been loaded or not like described in CSS tricks.

if (typeof jQuery === undefined) {
  //load jQuery
}
//the rest of code

UPDATE: See an example in my gist:

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top