Monday, March 25, 2013

CSOM in a CQWP

The post title explains it all!  I've been trying to put together some dynamic web page content based on items in a SharePoint list, using JavaScript code inside a Content Query Web Part on one of my site pages.  Shouldn't be so hard, right?

Well, turns out it isn't.  Found a nice link here with some of the steps needed:  http://techtrainingnotes.blogspot.com/2012/02/sharepoint-how-to-add-javascript-to.html - but with that code on my linked in JavaScript source file, the code still wasn't firing.

Here's what's needed.  At the bottom of the code, add in the following:
function myJSfunction {
   var clientContext = new SP.ClientContext.get_current();

}

function DelayUntilMyJSLoaded()
{
    ExecuteOrDelayUntilScriptLoaded(myJSfunction, 'sp.js');
}

_spBodyOnLoadFunctionNames.push('DelayUntilMyJSLoaded');

What these lines will do is to call my function, but only when the function is ready to be called based on having the base 'sp.js' file loaded.  If you do a view source on the hosting page, there toward the bottom you'll see something very similar.