Deploying and Using jQuery with a SharePoint 2010 Sandboxed Solution

If you’re an avid reader of this blog, you probably now that I’m quite a big fan of the jQuery Javascript library, especially in combination with SharePoint sites. For a while I’ve been trying to find a mechanism to deploy jQuery and add a reference to it on all SharePoint pages of a site, by just using a Sandboxed Solution. The first part, deploying the jQuery file, is really easy; this can be done in a Module in a SharePoint project. The second part was more of a challenge; making sure the jQuery file got referenced in all pages of a SharePoint site. My initial thought was to do this by using the AdditionalPageHead Delegate control, but it’s not possible in a Sandboxed Solution (you need to deploy the .ASCX to the SharePoint root). My second thought was to use the new ScriptSrc attribute you can use in a CustomAction (I wrote about this attribute some time ago). But initially I was under the impression that the ScriptSrc attribute could only target Javascript files loaded from the SharePoint Root (the \LAYOUTS) folder, resulting in a no-go for a Sandboxed Solution as well. Daniel McPherson stumbled upon this issue as well, but neatly solved it using Javascript to add the reference dynamically.

But apparently you can make use of the ScriptSrc attribute to reference files from the Virtual File System (e.g. a Document Library in a site) as well! (thank you Frederic Dobon for mentioning this!). The trick is to use the ~SiteCollection prefix in the ScriptSrc attribute, for example:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
    ScriptSrc="~SiteCollection/SiteAssets/jquery-1.4.2.min.js"
    Location="ScriptLink"
    Sequence="10">
  </CustomAction>
</Elements>

It’s that easy! For your convenience I’ve uploaded the source code and the resulting SharePoint Solution (WSP file) to CodePlex.

1 Comment

  • Hi Jan,

    It is very nice article. I am not much aware about share point but it will help my friends to do the task.

    I have also done some work on jquery. you can check it out on

    http://aspnet-ajax-aspnetmvc.blogspot.com/

    Thanks for sharing the good knowledge.

Comments have been disabled for this content.