One of the clients came to us with a pretty simple request. They need to display total item count of several views in a large SharePoint list using jQuery (more than 40,000 items). Normally, we would use APIs to retrieve information about lists and list items. In this case, SharePoint list object has an ItemCount property which returns the total item count of the list. Following is the code sample using list.get_itemCount() in ECMA. It is very efficient and fast.

If you need to get count number for a specific view, the performance issue may happen depending on the size of the list. We need to execute a CAML query to retrieve all items in a view. Since there is no item count property for CAML query, we will need to retrieve all items as SPListItemsCollection and use SPListItemsCollection.Count to get the count value. Following is the sample code using EMCA.

function GetListItemCount() {

currentcontext = new SP.ClientContext.get_current();

currentweb = currentcontext.get_web();

this.list = currentweb.get_lists().getByTitle(“Large List”);

var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(‘ ‘ +’Selected’ +’1400’);

listItems = list.getItems(camlQuery);

currentcontext.load(listItems);

currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),

Function.createDelegate(this, this.ExecuteOnFailure));

}

 

function ExecuteOnSuccess(sender, args) {

var count = this.listItems.get_count();

alert(count);

}

Beware that you need to specify the property in the CAML query. Otherwise, no results will be returned if the list items total count is greater than 5,000. Please refer here for tips to ensure queries are efficient and avoid query throttling. It took about 2 minutes to get item count for one view when I tested it on a list of more than 40,000 items…. FAR too slow.

A good alternative is to make use of the item count value in the view setting page from UI. First of all, we need to enable the group option and select proper group field to return the result as needed. Then we can use standard jQuery (no API calls) to go off and retrieve the HTML content from the view setting page. The following jQuery will grab the group tbody and walk down the DOM to retrieve the text value of each group. You can then sum up the values of each group to get the total count for the view if needed.

Written By:

softlanding

Softlanding is a long-established IT services provider of transformation, professional services and managed IT services that helps organizations boost innovation and drive business value. We are a multi-award-winning Microsoft Gold Partner with 13 Gold Competencies and we use our experience and expertise to be a trusted advisor to our clients. Headquartered in Vancouver, BC, we have staff and offices in Toronto, Montreal and Calgary to serve clients across Canada.

More By This Author