In Angular 10, the custom CSS URL is loading after the standard styles.css file

Below is the configuration from my angular.json file:

"options": {
            "outputPath": "dist/example",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": ["src/favicon.ico", "src/assets"],
            "extractCss": true,
            "styles": [
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/stylings/main.scss"
            ],
            "stylePreprocessorOptions": {
              "includePaths": [
                "src/stylings"
              ]
          },
            "scripts": []
          }

The issue I am facing is that in index.html, custom css is not being applied correctly. It first applies styles.css and then custom.css. How can I resolve this?

I tried using resourcesToLoad in index.html to order the loading of files but it is not working as expected.

 var resourcesToLoad = [
            {
            filename: "styles.css",
            elementType: "link",
            loadOrder: 1
        },
        {
            filename: "runtime.js",
            elementType: "script",
            loadOrder: 1
        },
        {
            filename: "polyfills.js",
            elementType: "script",
            loadOrder: 2
        },
        {
            filename: "scripts.js",
            elementType: "script",
            loadOrder: 2
        },
        {
            filename: "main.js",
            elementType: "script",
            loadOrder: 3
        }];

Here is the code snippet for adding custom css:

var domElement = undefined;
          if(CSS_ADDRESS){
              domElement = document.createElement("link");
              var loadStartTime = (new Date()).getTime();
              domElement.rel = "stylesheet";
              domElement.href = CSS_ADDRESS ;
              domElement.onerror = function () {
                  console.log("Load error for file: " + filename);
              }
              domElement.onload = function () {
                  var loadEndTime = (new Date()).getTime();
                  console.log('Custom CSS loaded in (ms): ' + (loadEndTime - loadStartTime));
              }
          }

Answer №1

To address the issue, we made modifications in the index.html file and adjusted the sequencing of CSS loading. While loading, we first check if a certain boolean value is true, then proceed to determine if custom CSS is enabled. If it is, we apply the custom styles; otherwise, we stick with the default CSS.

var resourcesToLoad = [
    {
        filename: "styles.css",
        elementType: "link",
        loadOrder: 1,
        requiresCustomCSS: true
     },
     {
         filename: "runtime-es2015.js",
         elementType: "script",
         loadOrder: 1
     },
     {
         filename: "polyfills-es2015.js",
         elementType: "script",
         loadOrder: 2
      },
      {
          filename: "main-es2015.js",
          elementType: "script",
          loadOrder: 3
       }
];

if (resource.elementType === 'link' && resource.requiresCustomCSS) {
   // To minimize the delay between loading base CSS and custom CSS
   var customElement = getCustomCSSElement();
   const head = document.getElementsByTagName('head')[0];
   document.body.appendChild(baseCSS_Element);
   customElement && document.body.appendChild(custom_CSS_Element);
}
else {
   document.body.appendChild(baseCSS_Element);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Eliminate Lower Borders from DataGrid Component in Material UI (mui)

I've been trying to customize the spacing between rows in a MUI Data Grid Component by overriding the default bottom border, but haven't had much success. I've experimented with different approaches such as using a theme override, adding a c ...

Customizing HTML element tags in MUI: Best practices

Using the most recent version of MUI (v5) and incorporating CssBaseline from @mui/materials. Typically, in CSS, I would set up my styles like this: body, html, #root { width: 100%; height: 100%; min-height: 100%; margin: 0; padding: 0; font-siz ...

Prevent the propagation of a particular CSS class's inheritance

I need to make modifications to an existing HTML5 app that features two unique themes. Here's an example of the current structure: <body class="theme1 theme2"> <div id="div1">I'm satisfied with both themes</div> <di ...

Create a jQuery animation that mimics the Safari home page experience. Create a

Is there a way to achieve a similar effect as Safari's new tab using HTML5 canvas instead of CSS3 3d transform? While we can create a similar transformation with CSS3 3D transform, it is limited to Webkit browsers. Can we use CANVAS to replicate this ...

The flipping CSS code will not be compatible with IE 11

I'm experimenting with creating a flip animation that reveals link text when images are flipped. Everything works fine in most browsers, except for IE11. Apparently there's an issue with transform-style: preserve-3d; in IE10, but being new to CS ...

Steps to easily modify the color of Font Awesome stacked icons when hovering over them

I have incorporated two Font Awesome icons into my design: fa-circle-thin fa-user-plus These icons are stacked to create a circular icon appearance. <span class="fa-stack fa-sm"> <i class="fa fa-circle-thin fa-stack-2x"></i> <i c ...

Changing the output of a service by using spyOn: A step-by-step guide

There is a specific service available: export class CounterService { random: any = { value: 123, date: 456, }; getRandom() { return this.random; } } A certain component utilizes this service. Within this component, the variable &apos ...

Exploring the dynamic duo of SystemJS and AngularJS 2

I am currently working on integrating the Core Angular2 module into my application, which is written in Typescript. It's essentially following the same structure as the quick start tutorial on the Angular.IO website. However, I am facing a challenge ...

What is the reason behind the input value becoming empty after a reset?

Currently, I am working with an input element reference: @ViewChild("inputSearch", { static: false }) This is how the template looks like: <input tabindex="0" type="text" (keydown)="keydownInputSearch($event)" #inputSearch autocomplete="off" ...

Struggling to figure out how to make this Vue function work

I am working with a list of tasks, where each task is contained within a div element. I am looking to create a function that changes the border color of a task to red when clicked, and reverts the previous task's border to normal. I have two files: &a ...

Utilizing JavaScript files within Angular2 components: A guide

I need to insert a widget that runs on load. Typically, in a regular HTML page, I would include the script: <script src="rectangleDrawing.js"></script> Then, I would add a div as a placeholder: <div name="rectangle></div> The is ...

Display PDF in Forge Viewer using PDF Extension - warning generated by pdf.worker.js

Whenever we attempt to display a PDF file using our own API, the pdf.worker.js generates a warning message and the PDF always appears completely white. https://i.stack.imgur.com/IqGML.png All I can see is this (it's a wide PDF that renders fine in t ...

What is the best method for creating a fade effect on a div background?

I am trying to animate a div with the id #test from a 0 opacity background to an opacity of 0.7 using CSS rgba values, but for some reason, the .animate function is not working as expected. Here is my CSS: #test { background-color: rgba(0, 0, 0, 0); ...

The struggle continues in attempting to adjust Angular Material 2 dialog positioning using MdDialogConfig

Does anyone know how to adjust the position of an MdDialog? openDialog() { let config = new MdDialogConfig(); config.height = '15px'; config.position.left = '5px'; let dialogRef = this.dialog.open(BasicAlertDialog, config); dialogRef. ...

I'm having trouble understanding why I keep encountering this error message: "SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…"

I am in the process of implementing a download button feature that will allow users to download a document from my node.js server. Check out this stylish button: https://i.stack.imgur.com/s4CjS.png For the front-end, I am utilizing Angular as the fram ...

Issue with Safari div not exhibiting proper overflow functionality

I'm looking to set up a webpage with a single sidebar and content area. Here's how I envision it: <div id="mainWrapper"> <!-- Sidebar --> <div id="sidebar"> <p>Sidebar</p> <p>Sidebar< ...

Creating a moving background for a loading bar with HTML5 and Shadow DOM is currently underway

Can anyone help with animating the progress bar using the HTML5 <progess> tag? I've been able to customize the Shadow DOM elements successfully, but I'm having trouble animating the background (repeating linear gradient). It seems to work i ...

Getting Started with Angular: Loading Data into a List from a Service

As I am relatively new to Angular, I have a list that needs to be displayed on the screen. Initially, I was able to show the list with hard-coded data, but now I need to fetch the data from my service that calls an API. The data retrieval part is already i ...

Exciting transition effect for font sizes in CSS

Issue: Hover over the X and wait for the div to collapse completely. Move away from the X Notice how the div jumps to the bottom and then back up. Inquiry: How can I prevent text wrapping while expanding the div during animation? (Currently using del ...

Creating a scrollable nested div on a mobile website

Is there a way to achieve a scrollable nested div on a jQuery mobile site? I am aiming for a fixed header and footer with the middle section being scrollable. Despite my attempts to set overflow:scroll (along with specifying the width and height of the div ...