Ways to load jQuery in SharePoint (2010/2013)(8 min read)

There are many different approachs to using jQuery with SharePoint. Here is a summary of several different methods I have used, including how to get it to play nicely with NuGet.

There are three main decisions to make:

  1. Decide where to put the jQuery files
  2. Add the jQuery (and other) library to the project
  3. Referencing the scripts

1. Decide where to put the jQuery files

i. In a site collection Document Library

Recently I have been putting scripts in the master page gallery, but putting them in Style Library is a common choice, as it is available across all templates (whereas libraries such as Site Assets are only in team sites). The feature needs to be activated to make the scripts available.

  1. In your Visual Studio SharePoint project, right click the project and select Add > New Item...
  2. Select Module, and use the name 'Scripts'.
  3. Configure an appropriate Site Collection (SPSite) level feature to reference the module; this can be a new feature, or added to an existing one.
  4. Rename Elements.xml to Scripts.xml (I like to give each Elements file a different name, so I can tell them apart in Visual Studio).
  5. In Scripts.xml, add Url="_catalogs/masterpage" or Url="Style Library/Xyz" to the Module element, where Xyz is whatever subfolder name you are using for this project, e.g.
    <Module Name="Scripts" Url="_catalogs/masterpage">

    OR

    <Module Name="Scripts" Url="Style Library/Xyz">

    Note that generally for the master page gallery I just use the root (which will put scripts into _catalogs/masterpage/Scripts) whereas for the Style Library I use a folder for the project (which will put the scripts into Style Library/Xyz/Scripts).

ii. Under _layouts

Available to everything on the server, this is also the location where many existing system JS files are located. One drawback is that it can't be used in sandbox solutions.

  1. On your development machine, go to C:\Program Files\Common Files\microsoft shared\Web Server Extensions\14\TEMPLATE\LAYOUTS
  2. Create a subfolder named Scripts (or it can be put in a company specific directory such as Xyz\Scripts).
  3. In your Visual Studio SharePoint project, right click the project and select Add > SharePoint Mapped Folder...
  4. Select TEMPLATE\LAYOUTS\Scripts.

iii. On a separate content distribution site

Update (2015-04-28):
A third option, particularly useful with SharePoint Online, this involves hosting the scripts in an Azure website or other content distribution location, e.g. https://xyz-content.azurewebsites.net/scripts/jquery-2.1.0.min.js

Deployment with this solution is a separate web application that contains the scripts needed, and which can use standard Web Deploy, or other techniques, to be deployed to Azure. The scripts still need to be referenced from SharePoint (step 3).

2. Add the jQuery (and other) library to the project

The folder name 'Scripts' was specifically used, because that is where NuGet packages such as jQuery put JS files. By using this name, the files can be automatically added.

  1. In your Visual Studio SharePoint project, right click and select Manage NuGet Packages...
  2. Select Online, enter 'jQuery' in the search box, and click the search icon.
  3. Select jQuery and click Install.

This will place the jQuery files into your Scripts folder. You can also install a specific version of jQuery if you want, via the Package Manager Console.

If deploying into _layouts, then nothing more is needed.

If jQuery is being placed in a library, then the files will have been automatically added to the Scripts.xml elements file, but you will want to update to make them GhostableInLibrary, e.g.

<File Path="Scripts\jquery-2.1.0.min.js" 
    Url="Scripts/jquery-2.1.0.min.js" Type="GhostableInLibrary" />

In SharePoint 2013, you can also mark the file with ReplaceContent (although this is more relevant for custom scripts that will change during development):

<File Path="Scripts\jquery-2.1.0.min.js" 
    Url="Scripts/jquery-2.1.0.min.js" Type="GhostableInLibrary" 
    IgnoreIfAlreadyExists="TRUE" ReplaceContent="TRUE" />

The same technique can be used to add any other desired NuGet script packages, and your custom scripts can also be added in a similar way.

3. Referencing the scripts

A. Referenced in a custom master page.

The key thing here if deploying to a library is to use a site collection relative link to the script, e.g. via the ScriptLink control in SP2013:

<SharePoint:ScriptLink language="javascript" 
    name="~sitecollection/_catalogs/masterpage/Scripts/jquery-2.1.1.min.js" 
    runat="server" Localizable="false" />

If the scripts are being stored in _layouts, then a relative ScriptLink can be used:

<SharePoint:ScriptLink language="javascript" 
    name="Scripts/jquery-2.1.0.min.js" runat="server" Localizable="false" />

You can also directly insert a script tag by breaking the reference up into a beginning and ending literals around a reference that resolves the path relative to the current site collection:

<asp:literal runat="server" 
    Text="<script type='text/javascript' src='" /><asp:literal runat="server" 
    Text="<% $SPUrl:~sitecollection/_catalogs/masterpage/Scripts/jquery-2.1.0.min.js %>" 
    /><asp:literal runat="server" Text="'></script>" />

B. Injected via a CustomAction.

A custom action can be used to add actions to the Ribbon, however it can also reference scripts. Although usually for scripts referenced by ribbon elements, this can actually load any script needed for the site.

  1. In your Visual Studio SharePoint project, right click the project and select Add > New Item...
  2. Select Empty Element, and use the name 'CustomActions'.
  3. Configure an appropriate Site Collection (SPSite) level feature to reference the module; this can be a new feature, or added to an existing one.
  4. Rename Elements.xml to CustomActions.xml (I like to give each Elements file a different name, so I can tell them apart in Visual Studio).
  5. In CustomActions.xml, add a ScriptLink custom action pointing to the script location, e.g.
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <CustomAction Id="Xyz.ScriptLink.jQuery" Location="ScriptLink" 
        ScriptSrc="~sitecollection/_catalogs/masterpage/Scripts/jquery-2.1.0.min.js" 
        Sequence="10010">
      </CustomAction>
    </Elements>

If the link is wrong (not found), then the page will still load as the script reference is injected directly as HTML, although the script request itself will 404.

A relative link (not starting with ~ or /) will default to the _layouts directory and use the ScriptLink control:

<CustomAction Id="Xyz.ScriptLink.jQuery" 
    Location="ScriptLink" ScriptSrc="Scripts/jquery-2.1.0.min.js" 
    Sequence="10010">
</CustomAction>

One drawback of the ScriptLink control is that if the file is not found, the whole page will fail with an error like: Cannot make a cache safe URL for "scripts/jquery-2.1.0.min.js".

Update (2014-12-15):
To add the custom action (at the Site Collection level) using CSOM, the following code can be used:

var customActions = clientContext.Site.UserCustomActions;
var jqueryAction = customActions.Add();
jqueryAction.Name = "Xyz.ScriptLink.jQuery";
jqueryAction.Location = "ScriptLink";
jqueryAction.ScriptSrc = "~sitecollection/_catalogs/masterpage/Scripts/jquery-2.1.0.min.js";
jqueryAction.Sequence = 10010;
jqueryAction.Update();
clientContext.ExecuteQuery();

C. Reference via a DelegateControl replacement

A common target for this is by replacing the AdditionalPageHead control. This will add jQuery to all pages in the site.

For an example of this technique, see: http://www.sharepointbriefing.com/features/article.php/3924951/jQuery-and-SharePoint-Part-I--The-Easy-Way-to-Load-the-jQuery-Library.htm

D. Reference via a custom Web Part

This involves creating a custom web part that add the reference to the script (such as via a ScriptLink or other control). It is useful if you only want jQuery available on one or two pages, wherever the web part is added. Be careful of multiple references to jQuery if you use this technique.

For an example of this, as well as the custom action approach, see Recipe 2 at: http://www.threewill.com/2012/01/adding-jquery-to-sharepoint/

E. Reference in user content

There are various content controls where HTML can be directly added. Probably the easiest in SP2010 is the HTML Form Web Part (in the Forms category), which allows direct editing of the HTML source (this can be less prone to error than the Content Editor web part). In SP2013, use the Script Editor web part.

<script type="text/javascript" 
    src="/sites/team1/_catalogs/masterpage/scripts/jquery-2.1.0.min.js" 
    ></script>

A downside of this approach is that the script source can't use the ~sitecollection token and needs to reference the correct path.

Recommendations

These days I tend to prefer deploying into a document library (method i), and then referencing in either a custom master page, if used (method A), or using the CustomAction trick, if there is no custom master (method B).

For SharePoint Online, consider deploying a content website in Azure (method iii), and then using A or B to reference the files.

6 thoughts on “Ways to load jQuery in SharePoint (2010/2013)(8 min read)

  1. I’ve added my jQuery assets to the Site Assets library. When I run fiddler each artifact is going through the authentication process. I see a 401 and a 304 on each one. What is this Can this be alleviated in some way?

    1. 304 shouldn’t be a problem, as it just means that the cached version hasn’t changed. If you are modifying files and want to force them to change, try adding a cache buster to the URL when referenced, e.g. “?v=”.

      You might want to incorporate this into your build process. More recently I have been concentrating on client side development, using the IonFar Migrations library, see my blog post https://sgryphon.wordpress.com/2015/09/02/sharepoint-online-continuous-deployment-with-ionfar-migration/ — if you follow the links to the project and look at the ‘TestApplication’ example you will see in the synchronise section how the hash can be automatically included in the scriptlink.

      The 401 is different; it would apply to unauthenticated users. Note that all files loaded into SharePoint document libraries are protected by authentication, so they aren’t accessible from non-SharePoint pages. If this is the case, consider option iii, to store the script files on a separate content distribution site. A separate site would be accessible both to authenticated and non-authenticated users.

  2. Hi Sly! Google brought me here and then I realized it was your site. Below is the jsom port of the custom action addition. Thanks for sharing

    var ctx = new SP.ClientContext();
    var site = ctx.get_site();
    var actions = site.get_userCustomActions();

    var newAction = actions.add();
    newAction.set_location(‘ScriptLink’);
    newAction.set_scriptSrc(‘~sitecollection/_catalogs/masterpage/s/init.js’);
    newAction.set_sequence(10010);
    newAction.set_title(‘init’);
    newAction.set_description(‘init’);
    newAction.update();

    ctx.executeQueryAsync();

    Regards

    M.

Leave a Reply

Your email address will not be published. Required fields are marked *