1

I am working on modifying modern site pages, more specific the top banner image in the title area. We want to set a max-width and center the background image. The CSS part I have figured out.

The issue I am facing is that the page loads/renders before my spfx extension loads the custom css.

export default class BannerImageStylingApplicationCustomizer
extends BaseApplicationCustomizer<IBannerImageStylingApplicationCustomizerProperties> {

@override
public onInit(): Promise<void> {

  SPComponentLoader.loadCss("https://xxx.sharepoint.com/sites/News/SiteAssets/BannerImageStyling.css");  
  return Promise.resolve();
 }
}

This means that the banner image is full-width for a second or two before my custom css is applied.

Is there any way I can modify the banner image before the page is rendered/loaded?

Any suggestions?

1 Answer 1

3

The problem you're having is that the loadCss method doesn't return a Promise or anything you can block on (in comparison loadScript does). So during runtime it starts to go get the css file and moves on to the next line right away.

A workaround could be to use fetch to go get the file first, which returns a promise you can block on. The browser should cache that request. And then use the loadCss API to "apply it to the DOM", which should be almost instantaneous given the fact it's loading from the local cache. Then again it's a workaround and might not work on all browsers and depends on your static assets delivery method.
Here is a code sample:

public async onInit(): Promise<void> {
    await this.context.httpClient.get("https://xxx.sharepoint.com/sites/News/SiteAssets/BannerImageStyling.css", SPHttpClient.configurations.v1);
    SPComponentLoader.loadCss("https://xxx.sharepoint.com/sites/News/SiteAssets/BannerImageStyling.css");
}

Also looking at your url, it looks like you're not leveraging any CDN to optimize the delivery of your static assets. You can leverage the office 365 CDN, it's free, and SPFx can deploy automatically the assets there if you enable includeClientSideAssets in the package-solution.json

1
  • Thanks - this is a workaround. From what I understand Microsoft is looking into this kind of feature but don't have any ETA.
    – TietjeDK
    Feb 1, 2019 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.