question

Toriyama avatar image
0 Votes"
Toriyama asked Toriyama commented

What is the best way to use external CSS in the SPfx solution?

In the project we have local CSS, but it would be nice to use an existing CSS on a website.
What's the best way to use this?

I know I can use it by adding the line below in the html.
<link rel="stylesheet" type="text/css" href="/sites/site/Documents/file.css" />

This works, but I don't know if it's the best.

Another way would be:
SPComponentLoader.loadCss("/sites/site/Documents/file.css");

This second way I haven't tried it yet, but it might be good.

What do you say?

Thanks

office-sharepoint-onlinesharepoint-devoffice-sharepoint-server-development
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

TongZhangMSFT-7548 avatar image
1 Vote"
TongZhangMSFT-7548 answered Toriyama commented

Hi @Toriyama,

Based on my research, you can follow these code to add external CSS Reference in SPFX Solution:

  1. import SPComponentLoader: import { SPComponentLoader } from '@microsoft/sp-loader';

  2. Add the code in onInit() method : SPComponentLoader.loadCss('https://xxx/xxx.css');

  3. Confirm that the project is building by running gulp serve

More information for reference:
https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/reference-third-party-css-styles#reference-third-party-css-stylesheets-from-url-in-the-web-part


If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.





· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @Toriyama,

I am checking to see if the problem has been resolved. If there's anything you'd like to know, don't hesitate to ask.

0 Votes 0 ·

Hi Tong.

I have used in my solution without javascript framework inside onInit() as below:

public onInit(): Promise<void> {
SPComponentLoader.loadCss("https://site.sharepoint.com/sites/site/Documents/file.css");
return Promise.resolve();
}

It looks good, but when I change something in the style.css it takes time to appear on the page that uses this css.
Maybe it's some CACHE? After a while everything seems to be ok.

Thanks

0 Votes 0 ·
sadomovalex avatar image
0 Votes"
sadomovalex answered

as far as I understood you need to load this external css dynamically. If yes check the following post: Dynamically Load a Stylesheet with React.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.