There are many correct ways (1, 2, 3, 4, 5…) of making scripts work with the Minimal Download Strategy Feature (MDS) in SharePoint 2013 and 2016. But to be honest – every time I need it, I get confused. So now it is time to find a simple solution for that.
Who is better at it than the developers of the SharePoint themselves? Look at the MDS code in the built-in Display Templates:
Let’s keep it as simple as Item_Default.js, let’s take it as it is and create our own scripts. Here is a skeletton of and MDS-ready script:
function runMyCode() { var time = new Date().toISOString(); console.log('runMyCode', time ); } runMyCode(); if (typeof(RegisterModuleInit) == 'function') { var scriptUrl = '/Style Library/runMyCode.js'; RegisterModuleInit(scriptUrl, runMyCode); }
Which boils down to this in pseudocode:
- Execute your code
- Determine if MDS is enabled
- If MDS is enabled
- Register your code for execution
That’s it. No more overcomplicating.
Related findings
External scripts (outside SharePoint Site Collection, from CDN) within ScriptBlock of a custom action (like AddJSLink in PnP) work withou any MDS-adjustments. The ScriptBlock adds a script tag to the head of the html document, and it the js reference is added to every AjaxDelta load. I would need more time to find out why. The good news is: it is an argument for using more CDN solutions in SharePoint.
Old stuff
A while ago I wrote two blog posts about MDS. Now I realise they were overcomplicated and the solution required customizations of the master page and 3rd-party scripts.
