Make SP.SOD.executeFunc and SP.ClientContext Function Properly In SharePoint 2013

During a long day of coding at work, I’ve been presented with a dilemma while writing code to execute JavaScript CSOM from a JSLink in a CustomAction. The code only executed if the page request was fresh from the address bar or refreshed, but didn’t when I clicked on a link to another page.

One thing to note is that this entire situation seems to occur only if the top ribbon is hidden. The ribbon itself executes CSOM calls, so the ClientContext object will always be available when it is visible.

According to http://msdn.microsoft.com/en-us/library/office/jj245759.aspx, entering the following code will load the sp.js file and then execute the function in the third parameter after the data is loaded.

// Make sure the SharePoint script file 'sp.js' is loaded before your
// code runs.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);

This worked for me only for new page requests, but not when I clicked on a link. After showing visible signs of frustration, I decided to try another method:SP.SOD.executeOrDelayUntilScriptLoaded

This method waits to execute the function that you’ve specified in the parameter until the script file is loaded, but doesn’t actually load the file. I noticed through debugging that if I place a break point on the original SP.SOD.executeFunc method and stepped through, it would work. I could replicate this behavior every time which led me to the conclusion that executeFunc is probably an asynchronous method (Correct me if I’m wrong). A light bulb finally kicked in after this realization.. “Why not use both?”

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { 
    console.log("Initiating SP.ClientContext") });
SP.SOD.executeOrDelayUntilScriptLoaded(someFunction,"sp.js");

Running the code above with a proper function implementation in executeOrDelayUntilScriptLoaded will work 100% of the time. I’m certain that I would have found a solution on the internet had I decided to search, but I like to take my own stab at things.

Next post, I will walk you through executing JavaScript files stored within a SharePoint List.