SP.Context Execution Order

We’ve hit a number of problems recently when using JSOM in SharePoint Online. Often when we try to execute a query we get strange errors such as “b is undefined”. It all relates to the SharePoint libraries we need not being available to us when we try to execute the commands. After some trial and error we seem to have a pattern that’s working pretty well.

Obviously the assumes you have JQuery but it is not necessarily needed.

$(document).ready(function () {
$("#loading-placeholder ").text("Loading...");
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', waitForSP);

function waitForSP() {
SP.SOD.executeOrDelayUntilScriptLoaded(retrieveListItems, 'SP.js');

function retrieveListItems() {
// run JSOM etc.