How to Enable Custom JavaScript on MDS Pages in SharePoint 2013

September 22, 2013

If you have custom JavaScript file loaded in your master page, as we usually do in SharePoint, you might have stumbled upon the problems with custom JS and SharePoint 2013 new Minimum Download Strategy (MDS).

By default, MDS is enabled on Team Sites in SharePoint 2013 and allows for refreshing data on SharePoint pages without causing reloads. But, in order to do so, all the content and JavaScript in MDS pages must play along nicely. If not, the symptoms include:

  • blank page on loading custom JS in a MDS-enabled page
  • custom JS script not loading

The solution

The first part is to use ScriptLink control in the master page, instead of using script tags directly. Specify "LoadAfterUI" attribute in order for the script to be loaded after the page is loaded in MDS.

<SharePoint:ScriptLink language="javascript" ID="Whatever" name="~sitecollection/Style Library/js/**yourcustom.js**" OnDemand="false" LoadAfterUI="true" runat="server" Localizable="false" />

The second part is to encapsulate all your custom JS in a single function and call it from your custom code. Your yourcustom.js file should look like this:

> function $\_global\_customjs(){  
>     \_spBodyOnLoadFunctionNames.push(**'DoSomething'**);  
> }  
>     var **DoSomething** = function ()  
>     {  
>         // --- Your custom JS here  
>     }  
> $\_global\_customjs();

Profile picture

Written by Edin Kapić Insatiably curious code-writing tinkerer. Geek father. Aviation enthusiast. Cuisine journeyman. Follow me on Twitter