Issues with getting the SP.ClientContext in SharePoint 2013

So, I’m migrating a solution from SP2010 to 2013. In the JavaScript for part of the solution, I use the JavaScript client-side object model (JSOM). This involves getting the current ClientContext for the site:

var clientContext = new SP.ClientContext.get_current();

Unfortunately, ClientContext was null, so I kept getting Null Reference exceptions.

“Weird”, I thought, “This worked in 2010″. Now, my solution has a very similar piece of code elsewhere in it, so I went and tested it – and it worked. Even weirder.

Next up, I tried using a SP.SOD.executeOrDelayUntilScriptLoaded() call around the code where I got the ClientContext. Surely it was just a matter of waiting for the JavaScript file ‘sp.js’ to load? Well, it never loaded. With these two lines…

SP.SOD.executeOrDelayUntilScriptLoaded(function () { alert('SP.Runtme.js Loaded'); }, 'SP.Runtime.js');
SP.SOD.executeOrDelayUntilScriptLoaded(function () { alert('SP.js Loaded'); }, 'SP.js');

…no alerts were shown. On the page that works, they both get shown nearly instantly.

Okay, so it’s not my code then, it’s that the JSOM isn’t initializing, but only on one particular page. That sucks. What can I do to initialise it? Well, I found this post describing the same problem, but for publishing pages. Mine isn’t – it’s an application page – but I suspected it might be the same issue. And I checked MSDN which describes initialising sp.js.

I added this line:

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

And my code began working again on this page. So it seems that for some pages in SharePoint 2013 the Client Object Model isn’t necessarily initialized.

One thought on “Issues with getting the SP.ClientContext in SharePoint 2013

  1. Dude. Thanks heaps.
    Couldn’t get to the link you posted but your solution works for publishing pages.

Comments are closed.