skip to Main Content

I have a requirement where there are many CSS files present on a CDN server and are publicly accessible.

My application built using Angular 17 needs to read a value from one of the query parameter and then hit that CDN server with CSS file URL to load the CSS file so that UI can be rendered according to the CSS file name provided in the application URL query parameter.

I have tried few options like loading CSS file using HttpClient in component ngOnInit, or using APP_INITIALIZER approach. I am able to load CSS file but this CSS does not apply on html.

I have used the achieved the same thing in AngularJS using

<link ng-href="https://<cdn-server-domain>/{{cssFileName}}.css">

but not able to find any working solution in Angular.

Please suggest.

2

Answers


  1. Chosen as BEST ANSWER

    The issue was due to slight delay between loading the remote CSS file and the browser actually applying the styles to the existing content, which was leading to a brief period where the page appears unstyled (Flash of Unstyled Content or FOUC).

    I got it solved using a Media Query with prefers-reduced-motion: no-preference This approach leverages a media query to trigger a brief style reset before the remote CSS is loaded. This can help hide the unstyled state while the CSS file is being fetched. E.g.

    /* Temporary reset to avoid FOUC */
    body {
      opacity: 0;
      transition: opacity 0.2s ease-in-out;
    }
    
    @media (prefers-reduced-motion: no-preference) {
      /* Your actual CSS styles here */
      body {
        opacity: 1;
      }
      /* ... */
    }
    

  2. Angular ignores <link> tags in your application, because styles usually should be part of your application’s CSS files. In your case this doesn’t work apparently. But you can dynamically create and append the tag to the DOM. Add this to your app.component.ts:

    ngOnInit() {
      const params = new URLSearchParams(window.location.search);
      const head = this.document.getElementsByTagName('head')[0];
      const link = document.createElement('link');
      link.href = `https://<cdn-server-domain>/${params.get('<param-name>')}.css`;
      link.rel = 'stylesheet';
      head.appendChild(link);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search