Remove lazy loading for a custom SPFx webpart

SharePoint Online is doing lazy loading when we hit a page with webparts. If you created a SPFx webpart, and if it’s not visible right after the page load, then it will only be loaded once the user scrolls to it…

To remove this behavior, and load the webpart as soon as possible, you must declare your webpart as a dynamic data source.

Here is the minimal code example (in pure JS, not in TS):

import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { DisplayMode } from '@microsoft/sp-core-library';

export default class HtmlViewerWebPart extends BaseClientSideWebPart {
  constructor() {
    super();
    // the below is used by the dynamic data source to avoid lazy loading
    this._sourceId = 'my_webpart';
  }

  onInit() {
    // to avoid lazy loading of the webpart, we register it as a dynamic data source
    // we only need to do it during the Edit of the page
    if (this.isPageInEditMode() && this.context.dynamicDataSourceManager) {
      this.context.dynamicDataSourceManager.initializeSource(this);
      console.log('Dynamic Data Source initialized to avoid lazy loading.');
    }
    
    return Promise.resolve();
  }

  isPageInEditMode() {
    return this.displayMode === DisplayMode.Edit;
  }

  // we need to declare this method because it's used by the data source to avoid lazy loading
  getPropertyDefinitions() {
    return []
  }

  // we need to declare this method because it's used by the data source to avoid lazy loading
  getPropertyValue(propertyId) {
    return propertyId;
  }
}

Then, edit the page, which will trigger the dynamic data source registration, and publish it.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*