CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: code sample

Make javascript code work with Minimal Download Strategy Part 1

I have a newer blog post about MDS, that provides a much simpler solution. Please check it before reading further.


mds_001

This is a part 1 of the blog post about Minimal Download Strategy and javascript adjustments for user code. What I initially thought should be enough for one post, is not enough, so I see it as a part 1. I wrote this post after I had read Chris O’Brien’s post about JSLink Here I want investigate how we can get his accordion list view working with MDS.

Minimal Dowload Strategy or MDS is a new feature in SharePoint 2013. By now, if you read this post, you already know about it. The simplest way to see if MDS is enabled on your site, you can recognize it on the “ugly” urls. I don’t think they are so ugly. But it is a matter of taste and habit.

No matter if you like MDS or not, MDS is enabled on many site templates and is a huge step towards a faster, more responsive architecture in SharePoint, I would say, towards the Single Page Application concept in SharePoint (but it is a long way to go).

We have to keep the MDS in mind, when we write our customizations in javascript. SharePoint 2013 loves javascript and the probability is high that you write a lot of javascript. If it doesn’t work with MDS, your code breaks and the user doesn’t see the functionality, or the site owner must disable the Minimal Download Strategy feature. I wouldn’t like to have disabling of an improvement feature as a prerequisite for my code.

In this blog post I want to dig into the techniques for getting the javascript code working with MDS. For a while ago I read a wonderful blog post in Chris O’Brien’s blog:

There he describes how JSLink works and how much you can change a standard XSLTListViewWebPart. Chris creates a jQuery UI Accordion view for his list view. As an issue he mentions the MDS.

Here I want to take Chris’ code and adjust it for MDS. My goal is to change as little as possible to find the most important steps for MDS. So I’ll continue where he has finished.

My colleages who have debugged the MDS a lot, gave me a tip: $_global. The SharePoint 2013 internally uses function inside the files which starts with $_global:

mds_002

Here we have callout.js/callout.debug.js The function is called $_global and _ and the filename callout = $_global_callout. Then the function is invoked directly in the end of the file. It is a different story than the anonymous self executing funcitons we’ve seen before.

When I search the hive folder with grepWin tool, I find 148 files containing “$_global”:

mds_003

I rewrote the the code into one wrapper function and invoked in the end of file:


// function to setup JSLink templates
function $_global_AccordionListView() {
    // function to process an accordion item..
    window.COB = window.COB || {};
    window.COB.accordionItem = {
        customItemHtml: function (ctx) {
            var accordionItemHtml = "</pre>
<h3>" + ctx.CurrentItem.Title + "</h3>
<pre>
";
            accordionItemHtml += "</pre>
<div>" + ctx.CurrentItem.AccordionItemDescription + "</div>
<pre>
";
            return accordionItemHtml;
        }
    };

    var overrideCtx = {};
    overrideCtx.Templates = {};

    overrideCtx.Templates.Header = "</pre>
<div id="\&quot;accordion\&quot;">";
 overrideCtx.Templates.Item = window.COB.accordionItem.customItemHtml;
 overrideCtx.Templates.Footer = "</div>
<pre>
";

    overrideCtx.BaseViewID = 1;
    overrideCtx.ListTemplateType = 11000;

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);

    $(document).ready(function() {
	    // It seems SharePoint inserts a script tag in an inconvenient place that breaks jQuery UI's accordion, so let's remove it!
		// (N.B. further testing recommended for production)..
		$("#accordion").find('#scriptBodyWPQ2').remove();

		$("#accordion").width('70%');
		$("#accordion").accordion();
	});
}

$global_AccordionListView();

Unfortunately, it didn’t help. There was still no accordion. But wait, is it just the accordion that isn’t created. Indeed. The JSLink itself works. We can see it in the markup:

mds_004

Strange, maybe there was no need for rewriting the code in this case. I changed back all the javascript code to see the markup. It is the right markup. Then the problem is the accordion initialization, or the $(document).ready. Then I thought about the SharePoint-function for that: _spBodyOnLoadFunctionNames and rewrote the $(document).ready:

function onReady() {
    $("#accordion").find('#scriptBodyWPQ2').remove();
    $("#accordion").width('70%');
    $("#accordion").accordion();
}

_spBodyOnLoadFunctionNames.push("onReady");

When I deployed it, it worked… It doesn’t seem like it is the whole solution. It is too simple. Well, it is the solution for the Accordion List View. By putting the accordion initialization code into _spBodyOnLoadFunctionNames we ensure that SharePoint runs it even on pages with MDS. As the name tells us: OnLoad. This appends the code to the onload function which runs after the $(document).ready. It means the time before the text becomes an accordion is longer.

Other cases

Allright, the actual jslink works pretty fine with MDS, except the accordion. But if we hadn’t the jQuery UI Accordion, there wouldn’t be a need to make change to the javascript code. There must be other cases where we need to adjust our javascript code. In the meanwhile I discovered a couple of files in the hive folder which use RegisterModuleInit function:

mds_005

After a quick search I found this:

Sridhar writes in his post, you have to have your javascript code in a function, then call the function inside a RegisterModuleInit. It is strange. Chris O’Brien’s example makes almost the same thing as Sridhar, it changes the display with JSLink. But there was no need for RegisterModuleInit.

More investigation will be in part 2.

Thanks to my colleagues Christopher, Björn and Martin for giving me tips and discussing it with me.

A simple Log for ULS

Here is a simple log which has been inspired of Android Log. It logs to ULS which you can open with ULSViewer, SharePoint Log Viewer.

using System;
using Microsoft.SharePoint.Administration;

namespace Contoso.Intranet.Portal.Utilities
{
    public class Log
    {
        private static readonly string _CATEGORYNAME = "CONTOSO";
        private static readonly SPDiagnosticsCategory _ERROR_CATEGORY = 
              new SPDiagnosticsCategory(_CATEGORYNAME, TraceSeverity.Unexpected, EventSeverity.Error);
        private static readonly SPDiagnosticsCategory _WARNING_CATEGORY = 
              new SPDiagnosticsCategory(_CATEGORYNAME, TraceSeverity.High, EventSeverity.Warning);
        private static readonly SPDiagnosticsCategory _VERBOSE_CATEGORY = 
              new SPDiagnosticsCategory(_CATEGORYNAME, TraceSeverity.Verbose, EventSeverity.Verbose);
        private static readonly SPDiagnosticsCategory _INFO_CATEGORY = 
              new SPDiagnosticsCategory(_CATEGORYNAME, TraceSeverity.Medium, EventSeverity.Information);

        private static void WriteTrace(SPDiagnosticsCategory category, string message, string trace)
        {
            SPDiagnosticsService.Local.WriteTrace(0, category, category.DefaultTraceSeverity, message, trace);
        }

        public static void Error(Exception ex)
        {
            WriteTrace(_ERROR_CATEGORY, ex.Message, ex.StackTrace);
        }

        public static void Warning(string message)
        {
            WriteTrace(_WARNING_CATEGORY, message, "");
        }

        public static void Verbose(string message)
        {
            WriteTrace(_VERBOSE_CATEGORY, message, "");
        }

        public static void Info(string message)
        {
            WriteTrace(_INFO_CATEGORY, message, "");
        }

    }
}

A possible improvement can be a custom Area. See an example of ThorstenHans on Github: CustomLogger.cs

EDIT: I found an interesting article: How to log to the SharePoint ULS Logs: Clean Debugging and Error Logging broken down into steps written by Philip Stathis.

Discovering SharePoint

And having fun doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

RealActivity - Real-time and trustworthy

Blog site of founder, RealActivty - Paul J. Swider

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

.:paul.tavares:.

Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint

blksthl

Mostly what I know about SharePoint - CommunicoCuspis