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

The `d-flex flex-column` is causing the image within the div to be hidden

The setup looks like this: <div className="d-flex flex-column"> <div> Text </div> <div style={{ backgroundImage: 'url(...)' }}> </div> </div> The URL is functioning correctly. The div element is ...

Display a single image on the tablet and a distinct image on the computer

Currently, I am encountering an issue with my webpage located at . The problem lies in the right upper corner where a ribbon is located. However, when viewing the page on a tablet, the ribbon overlaps with my menu. To resolve this, I thought about displa ...

Safari IOS experiencing issue with element disappearing unexpectedly when input is focused

I am facing a situation similar to the one discussed in the question (iOS 8.3 fixed HTML element disappears on input focus), but my problem differs slightly. My chatbox iframe is embedded within a scrollable parent, and when the iframe is activated, it exp ...

"Enhancing Your List Design: Customizing CSS for Hover Effects on Images

I'm currently working on a CSS/HTML list that utilizes an image as the background and changes to a different image when hovered over. However, I've encountered an issue where the hover image is not aligning properly, leaving a noticeable gap. T ...

Encountering an error while unit testing Angular components with MatDialog: "Error: <spyOn>: open has already been spied upon."

Once I create an HTML file with a button, I trigger a poll to appear after an onClick event. Then, when the "submit" button is clicked on the dialog window, it closes and I intend to execute subsequent methods. In my TypeScript file: openDialogWindow() { ...

Having all elements at the same height

I am looking to enhance my JavaScript code to only impact 4 items at a time. The goal is to target the first 4 instances of .prodbox, adjust their height accordingly, then move on to the next set of 4 and repeat the process. This sequential adjustment will ...

What's causing the text not to wrap when using float?

I've tried setting float:left for the image and float:right for the text, but the image is still overlapping the text. What I really want is for the text to wrap around the image - to be on the right side of the image at the beginning and below the i ...

align the text below a single element

Whenever I attempt to designate the character c as sub-aligned within a table row, the subsequent bar text also becomes sub-aligned (which is very counterintuitive). <table> <tr> <td>test</td> <td>foo<sel style= ...

Is it possible to partially move the image outside of the MUI dialog?

Is it possible to move an image partially outside of the MUI dialog, with the bottom part inside and the top part outside the dialog? I attempted a solution found on Stack Overflow but it did not yield the desired result. This is the dialog code: <Dial ...

"Difficulties with Tribute Page Project on FreeCodeCamp: HTML and

I am currently working on a tribute page for a challenge from FCC and I am facing some issues with adding padding to my .life and .work divs in the HTML and CSS code above. Despite spending a few hours searching for solutions online, I have not been able ...

Toggle the visibility of table rows based on a specific class using a checkbox

I am currently working on a code that displays the results of a query in a table format. I would like to have the ability to click on certain elements to show or hide them. I know this can be achieved using toggle and CSS, but I keep encountering obstacles ...

Error encountered in lodash.js in Angular 2 framework

I have been attempting to implement lodash for a datatable. Here are the steps I followed: First, I tried running npm install lodash, but encountered an error stating that the package could not be found After researching the issue, I attempted npm in ...

I'm struggling to transfer information from my form to TypeScript in Angular

Currently, I am working on developing a fullstack application using Node.js and Angular (material UI). However, I have encountered an issue that I need help with. I am trying to figure out how to retrieve data from an Angular form for a small web resource ...

Utilizing Angular 6 and JavaScript to invoke two functions within an (ngClick) event in both the Component and JavaScript

I have a requirement to execute two functions in my click event, one for my component and the other for a custom JavaScript function. Here is the code snippet: Angular click event: <button type="button" class="btn btn-primary" (click)="Plans(); " [att ...

Issues with arranging DIV elements using CSS

I have organized a few DIVs within a parent DIV. I am trying to make them align horizontally, but despite my efforts, they remain stacked vertically. Here is the code snippet: <style> #entrycontainer { height: 100px; width: 500px; } #entry ...

Difficulty with Script Causing Margin Bottom to Fail

Check out my website at this link. Below is a div I have created: <div class="home" style="background-image: url(http://payload51.cargocollective.com/1/7/237315/3336908/HomeImage_o.jpg); background-attachment: fixed; height: 660px; width: 100%; opacit ...

Angularjs directive retrieves infowindow DOM element from Google Maps

In order to apply some style fixes to the Infowindow, I am trying to select the element with the class 'gm-style-iw'. This selection process is taking place within an angularjs directive. <div ui-view="full-map" id="full-map" class="mainMap c ...

What methods can I use to ensure my images are optimized for mobile users?

I have gone through several other discussions related to this issue, but none of the suggested solutions are working for me. Even with max-width: 100% and height: auto, the images remain unresponsive. They appear fine on browsers like IE, FF, and Chrome on ...

Switching Styles in React applications

I am currently developing a React application and I have multiple stylesheets to restyle the same elements. For the purpose of this query, let's assume that I have two stylesheets with identical elements but different styles. Presently, in my app, I i ...

Manipulating divs by positioning them at the top, left, right, bottom, and center to occupy the entire visible portion of the page

Many suggest avoiding the use of table layouts and opting for divs and CSS instead, which I am happy to embrace. Please forgive me for asking a basic question. I am looking to create a layout where the center content stretches out to cover the entire visi ...