SharePoint Framework is all about rendering stuff on the client side, avoiding the long overdue ASP.NET Web Forms technology that SharePoint (Online) is still fundamentally based on. When rendering things client side everything is done asynchronously, to avoid locking down the UI threads and having a user experience that is fluent.
In order to give the user good feedback that things are happening in the background, you need to have some kind of visual cue that tells the user - hey I’m doing stuff now, gimme a minute. There are thousands of different ways to do this and everyone does it differently; ranging from animated gifs to “loading” texts. And everyone using different methods does not always help with the user experience - so why don’t we have a common way to do this?
We actually do have this built into the SharePoint Framework!
The SharePoint Framework Loading Indicator
The SharePoint Framework contains a set of nifty methods that we can use to show a loading indicator in standardized and common way.
The SharePoint Framework contains a special interface and corresponding implementation that is called IClientSideWebPartStatusRenderer. This interface defines two methods:
- displayLoadingIndicator(domElement: Element, loadingMessage: string): void;
- clearLoadingIndicator(domElement: Element): void;
The first one, displayLoadingIndicator, is used to create a loading indicator with a spinning wheel and a loading text and then replace the inner contents of a HTML element with that code. For instance, for client-side Web Parts that is loading data dynamically should use this as one of the first things in the render() method. The second one, clearLoadingIndicator, does the opposite, it removes the loading indicator.
The IClientSideWebPartStatusRenderer is always accessible through the IWebPartContext, that is on the context object of your Web Part.
Here’s an example on how to use it:
public render(): void {
this.context.statusRenderer.displayLoadingIndicator(this.domElement, strings.Loading);
this._webInfoProvider.getWebInfo().then((webInfo: IWebInfo) => {
this.context.statusRenderer.clearLoadingIndicator(this.domElement);
this.context.domElement.innerHTML = `<h1>${webInfo.title}</h1>`;
});
}
As you can see the first things we do is to replace the whole client side Web Part with the loading indicator and a loading message. Then once our Web Part is done and have data to render, we clear out the loading indicator before rendering our stuff. In this case it is a redundant operation to clear the loading indicator, since we are replacing the whole Web Part HTML with our custom rendering. If we had a more advanced user interface we could put the loading indicator in another of our elements and then remove it.
And this would be how it looks like in the SharePoint Workbench, when loading for 2 seconds.
You can get a copy of all the code at this Github repository: https://github.com/wictorwilen/spfx-nuggets
Happy Web parting!