Testing

webTiger Logo Wide

Developing SPA Apps in SharePoint with JavaScript

SharePoint 2013 Logo

Recent versions of SharePoint have exposed a rich tapestry of options for interacting with it without needing to resort to server-side code-based solutions. The main ones that I’m going to talk about here are the JavaScript Object Model (JSOM), SharePoint Web Services, and the RESTful API.

In this article:

Introduction

Developing rich internet applications (RIA) for SharePoint as Single Page Applications (SPA) can be achieved using just JavaScript and HTML (and SharePoint Designer!) It is probably worth mentioning, at this point, that the best way to deliver such solutions nowadays will usually be by developing a SharePoint Add-in, but that’s beyond the scope of this article as we want to concentrate on just getting something working rather than having to package it up and deploy it as a reusable construct.

SharePoint’s JSOM is a client-side API that offers a broad set of features for interacting with SharePoint lists, etc. and where this functionality falls short, which it does on occasion, you can normally use jQuery AJAX with SharePoint web services or SharePoint’s RESTful API to fill the gap.

One of the most common criticisms that have historically been levelled at ‘applications’ developed using SharePoint is clunkiness. Don’t get me wrong, it is a great, diverse, product that empowers end-users to create solutions using sites, lists, workflows, etc. without needing to involve seasoned software programmers. The trouble is that most of the user interfaces (UI) (e.g. new/edit/display forms, list views) are slow to load, sometimes non-responsive for a while, and generally the cause for grumbling – in my experience of the feedback received from end-users at least.

So, how does the JSOM API and supporting web services, etc. make it any better? Well, for any half decent web developer, it puts control of the UI fully in your hands by offloading the data query work to JavaScript calls instead of having to rely on functionality built into out-of-the-box (OOB or OOTB) web parts, etc. This allows for the potential to develop a much richer user experience (UX), with loading spinners, interactive loading and updating of regions of pages, etc. Even better, you can also develop using your preferred JS API (Angular/React/etc.) for a truly interactive and scalable development environment.

Seasoned SharePoint developers, who have lots of experience with coding solutions (in C#. etc.), may argue you have been able to do this for ages in older versions of SharePoint. To some extent that’s true, but you were often limited in what you could do from a UI/UX perspective and it nearly always meant resorting to code-based solutions that needed to be built, deployed and activated, and debugging could often be painful too. JSOM makes a lot of this much easier. You can debug your code in the web browser debugger, and even simulate interaction with SharePoint quite easily (as I’ll demonstrate later on) so you don’t have to work with the server at all for a significant portion of your development lifecycle.

(Back to Top)

Choose Your Weapon(s)

When working in JavaScript (or even TypeScript) in SharePoint, you’ll first need to decide which of the available SharePoint APIs you want to use.

Pretty much all of them will require you to get used to asynchronous calls, as that’s how most of them work, and this isn’t a bad thing as it helps to keep the web app responsive while queries are being sent to and responses returned from the server.

The oldest, and still supported API (even on SharePoint Online at the time of writing) is what has come to be referred to as SharePoint’s classic web services. You can normally identify calls to these services because they have an .asmx extension on their name.

Then there are two lots of RESTful API web services: the legacy ones from circa SharePoint 2010, which use the old /_vti_bin/api web-site relative URLs (e.g. _vti_bin/api/listdata.svc); and the more more modern RESTful API that Microsoft now advocates as the preferred one to use.

Finally, there’s SharePoint’s JSOM (JavaScript Object Model), which was supposed to be a successor to the earliest REST API, was pushed heavily by Microsoft for a period of time as the recommended development mechanism, and has since been abandoned and isn’t even being officially supported anymore. Because MS promoted use of JSOM for quite a while, you are still likely to come into contact with it when working with existing code bases for a long time to come.

Microsoft now once again recommend their latest REST API, and for that reason… so do I. 😉

The SharePoint JavaScript Object Model

If you come from a background programming in CSOM (SharePoint’s Client Object Model for .NET), then the first thing you’ll probably notice with JSOM is that they have done away with the synchronous calls. You won’t be able to call ‘ExecuteQuery’ like you can in CSOM, and will need to implement asynchronous callbacks using JSOM’s executeQueryAsync instead.

Until you get used to it, JSOM can seem a little counterintuitive as you essentially need to queue up requests/commands and then execute them. For example, if you wanted to get all fields from a list it might go something like this:

// Make the calls to get the list's field specifications...
var context = SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle('MyListName');
var fields = list.get_fields();

// NOTE: if you try to use the list or fields variables at this point you will
// likely get an execution error as they are only queued up to be loaded with
// the data - no query has been executed yet!

// Make the async call to process the queued data request(s)...
context.load(list);
context.load(fields);
context.executeQueryAsync(
    function (sender, args) {
        // success-event-handler: do something with the data 
        // (you can now use list and fields variables!)
    },
    function (sender, args) {
        // failure-event-handler: use args.get_message() and args.get_stackTrace() 
        // to view/log the error, and handle the error as necessary
    }
);Code language: JavaScript (javascript)

This is the case when writing data to SharePoint too… you queue up what you want to do first, and then execute the actions asynchronously and wait for SharePoint to return the outcome.

Something you will come across a lot when working with the JSOM API is how difficult it is to find information on it (especially now it is being deprecated). Your best bet is to look here in the first instance, assuming the MS link still works, and most of the useful details about JSOM were in the Core → SP.Debug.js section at the time of authoring).

If you are using JSOM then you’ll likely need to query lists and items, and pre-filter the results server-side to reduce your data I/O footprint. Microsoft provides the ability to define filters using CAML (Collaborative Application Markup Language), which is XML style markup with specific rules. Again it can be a little painful finding information on CAML, so your best starting point is here.

Something that tripped me up with CAML in the early days was the And and Or conditions, because each one requires EXACTLY two terms inside it. In order words, if you want to ‘And’ together 4 different filtering conditions you need to use 3 nested And blocks to achieve it, something like this:

<And>
  <Eq><FieldRef Name"Field1"=""><Value Type="Text">Val1</value></Eq>
  <And>
    <Gt><FieldRef Name"Field2"=""><Value Type="Text">2014-09-30</value></Gt>
    <And>
      <Eq><FieldRef Name"Field3"=""><Value Type="Text">Val3</value></Eq>
      <Eq><FieldRef Name"Field4"=""><Value Type="Text">Val4</value></Eq>
    </And>
  </And>
</And>Code language: HTML, XML (xml)

Also, techniques for making your users aware stuff is loading/processing in the background and how use of the setInterval() method is crucial to a good user experience.

Aside: it is worth mentioning that Microsoft were pushing JSOM as the preferred development API for while (a long time ago now), but have since abandoned it in favour of the REST API and SPFx. JSOM is no longer being actively maintained and will probably stop being supported by SharePoint Online at some point in the future.

(Back to Top)

SharePoint RESTful API

When we talk about SharePoint’s ‘RESTful API’ nowadays we are talking about the modern one. Queries and commands are well organised in a structure of resources that any developer used to REST would be comfortable with, but it may feel a larger jump for SharePoint Developers more used to JSOM/CSOM.

Here are some example REST calls:

https://fabrikam.sharepoint.com/_api/web/lists(guid'{listId}')

https://fabrikam.sharepoint.com/_api/web/lists/GetByTitle('MyListName')

https://fabrikam.sharepoint.com/_api/web/lists/GetByTitle('MyListName')/itemsCode language: plaintext (plaintext)

All 3 examples above are simple HTTP-GET requests.

The first example above will perform request based on knowing the list ID (GUID), retrieving information about the list properties (title, number of items, base-type, etc.)

The second example will return the same data as the first example, except it uses the list’s current display title to identify/locate the list.

The third example will return details for the items in the ‘MyListName’ list.

Something to point out is that where CSOM/JSOM tend to return all the data requested, the REST API will page the data being returned. 100 items at a time will be returned, and it is possible to check if more pages are available and request them via a property (‘__next’) of the current dataset being returned. The ‘__next’ property specifies the full URL required to request the next page of data, or is omitted if no further pages are available.

(Back to Top)

Improving the User Experience

One of the immediate advantages of pushing UI rendering client-side is the performance gains that can be achieved. You reduce load on the server by getting the client (typically a web browser) to do most of the rendering work and reduce the majority of interaction with SharePoint to data queries and updates.

Using RIA (Rich Internet [Web] Application) and SPA (Single [Web]-Page Application) programming techniques a rich and functional app can be hosted on SharePoint without using hardly any of SharePoint’s own server pages.

Breaking away from SharePoint’s own UI/UX constraints and embracing a full web programming experience also greatly extends what can be done on SharePoint too. Using jQuery and Bootstrap, and optionally a JS frameworks like AngularJS and ReactJS, will immediately make your ‘app’ look less SharePoint-like and more dynamic and app-like.

Behind the scenes data can still be hosted on SharePoint in lists/libraries and SharePoint itself will still be used to authenticate the user (preferably via SSO (Single Sign-On) if possible for a more seamless UX). Even better, if SharePoint’s reporting services are installed then extensive reporting can easily be performed on the data too including linking to Microsoft’s Power BI if being hosted in the cloud (or if the organisation has a reverse proxy configured to allow Power BI access to the on-premise SharePoint farm).

Custom apps can even be packaged as SharePoint Add-ins to make them easy to deploy and update/upgrade.

(Back to Top)