SharePoint 2013: Working with sp.js files and Publishing pages

So you are trying to write Javascript code in SharePoint 2013 and want to load the sp.js file before your custom function is called. And for that you have used.

ExecuteOrDelayUntilScriptLoaded(“your javascript function”, "sp.js");

But it’s not working. Sad, isn’t it ?

The reason is that, with SharePoint 2013 publishing pages the above syntax doesn’t work. You need to register using the below syntax

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', “your javascript function”);

I struggled 2 hours to find this MSDN article which showed me the right way.

Retrieving SharePoint List Items using Javascript in a Custom Webpart

So you want to fetch list items but do not want any post back, yes we can implement that using Javascript within our custom webpart by using a client control. 

Let me explain that in a step by step process
  • Create a new Visual Webart Project in VS 2012.
  • Give it a proper name and make it a Farm level solution.
  • Now delete the existing Visual WebPart item within the solution (to remove the default name) and add a new item – Visual WebPart and give it the desired name.
  • Open ascx file and copy paste the code below









Test


function fetchListItems()
{
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('List Name');
//I am fetching the list items randomly from the first 30 items
var randomNumber = Math.floor((Math.random() * 30) + 1);
var camlQuery = new SP.CamlQuery();

//increase the number within the RowLimit tag to fetch the number of items you wish
camlQuery.set_viewXml('' +
'' + randomNumber + '1');
this.collListItem = oList.getItems(camlQuery);

clientContext.load(collListItem);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded(sender, args) {

var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();

while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() +
'\nTitle: ' + oListItem.get_item('Title') +
'\nBody: ' + oListItem.get_item('Body');

}
alert(listItemInfo.toString());
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Here I am using client control and not any server control so there will not be any post back experience.
If you wish you can add more functionality to this same webpart and use it in your real world scenario like adding server controls to it and then writing some code behind for it and so on.