Sep 4, 2015

Using SharePoint Client Context JavaScript on Publishing Site

In order to use SharePoint Client Context (SP.ClientContext) in your own custom Javascript on a pafe, you need to ensure that sp.js is loaded. This is an onDemand file, which means it is loaded only when needed, i.e. when the browser requests it. In most cases it gets loaded because of something, most commonly the ribbon, on the page, so it is sufficient to start your custom Javascript with

ExecuteOrDelayUntilScriptLoaded(CustomFunctionUsingContext, "sp.js");

On Publishing sites, however, when the page is published, ribbon is hidden and sp.js does not get loaded unless there is some other code on the page to demand it. Thus, you might need to use a bit of force to get sp.js loaded. That is, you need to demand it yourself. The function for this would be

SP.SOD.executeFunc("sp.js", "SP.ClientContext", CustomFunctionUsingContext);

or

SP.SOD.executeFunc("sp.js", "SP.ClientContext", function(){
 YourCustomCodeHere
}); 

This is exactly what I was trying to use when inserting a code snippet on a Publishing page, using the Client Context to retrieve subwebs, for some odd reason the above did not do it, so I tried something that seemed totally crazy:

SP.SOD.executeFunc("sp.js", "SP.ClientContext", function(){
 ExecuteOrDelayUntilScriptLoaded(CustomFunctionUsingContext, "sp.js");
});

Strangely enough it started working after that. Later on, when none of the above seemed to work on a team site, except in page edit mode, I started to wonder if the problem really was this or something within SharePoint (throttling thresholds, script not loading every time, whatnot). I am not inclined to change it anymore since now it works. Anyway, might be wise to add some code there to avoid being throttled or blocked by SharePoint

No comments: