jQuery support in SharePoint 2013

Author by Eric Franz

jQuery is supported in SharePoint 2013, but it’s just JavaScript so it should be, right? Well, there is at least one case where it doesn’t work, and I want to show you. Consider the following jQuery code for document ready and a vanilla style change:

$(function () {
    $("body").css("background-color", "red");
});

This will work 99% time, but not when an assetpickers.js is also used. Say for example you have a publishing page with the above jQuery block on it. This jQuery code will run fine until you put the page in edit mode. Once the page is in edit mode, SharePoint 2013 includes assetpickers.js to your page. Here is a snippet from assetpickers.js, see if you can find the problem:

c;b.appendChild(a)}function $(){a:;for(var c=[],b=0

That’s right, the $ function is reinitialized and there is a conflict in the global namespace. So instead of $ being a jQuery implementation as so:

function (a,b){return new p.fn.init(a,b,c)}

It becomes the assetpickers.js implementation (minified) which is:

function $(){a:;for(var c=[],b=0;b

The error you will actually see because of this is a scripting error similar to:

Uncaught TypeError: Cannot call method 'css' of null

Where the ‘css’ in the error message will be replaced with whatever actual jQuery method you are actually calling (animate, hide, etc). This is because calling $() will now return null and the method chain to .css() will cause a null reference exception.

Solution

The good news is there is a solution to this issue (without waiting for MS to fix this). The solution is to stop using the $ method and instead use the jQuery method for your code. So the above code would become:

jQuery(document).ready(function () {
    jQuery("body").css("background-color", "red");
});

You could stop there, but you may want to also consider calling jQuery.noConflict() to release control of the $ variable because any code using $ will fail anyways (until it’s refactored), unless you can ensure it executes before SharePoint 2013 alters the $ implementation; and using noConflict() may demonstrate better intent in your codebase from a maintainability perspective. However, if you have a lot of 3rd party plugins and don’t want to refactor them to use a fully qualified jQuery prefix, you may want to detect the page is in edit mode and elect to use less jQuery at that time.

Author

Eric Franz

Modern Applications Solution Lead