1

Background

  • I have two css files - styles.mobile.css and styles.desktop.css
  • As the name suggests, I am using two separate css for mobile and desktop views
  • I inject css dynamically in index.html based on screen size
  • Obviously I can't put them in styles.css
  • I have attached folder structure screenshot

Question Is there a way to add hashing to styles.mobile.css and styles.desktop.css when I run ng build --prod

Code to detect device and inject css

 private addCss(): void {
    if (this.currentDevice === "desktop") {
      this.document
        .getElementById("theme")
        .setAttribute("href", "styles.desktop.css");
    } else {
      this.document
        .getElementById("theme")
        .setAttribute("href", "styles.mobile.css");
    }
  }

enter image description here

6
  • Can you post your index.html on how you detect it? Commented Jun 11, 2018 at 6:33
  • Why don't you use single css and add media query to differentiate css based on screen size? Commented Jun 11, 2018 at 6:36
  • I don't see why you can't put them into your style.css file. Make a media query and you're good to go. Commented Jun 11, 2018 at 6:37
  • @trichetriche Both styles.mobile.css and styles.desktop.css are altogether different. So I decided to have two separate manageable css instead of single giant file. Commented Jun 11, 2018 at 6:43
  • Doesn't change the fact that you can create a single file that import both separate files, and use media queries to chose which one to use. Commented Jun 11, 2018 at 6:46

2 Answers 2

1

Add "ng build --prod --output-hashing all", hash contents of the generated files and append hash to the file name to facilitate browser cache busting

Sign up to request clarification or add additional context in comments.

1 Comment

no it works only for js, it is not adding the hash to our css in angular and it causes issue in the browser's cache.
0

You need to manage your css files on a stylesheet rather than on your index.html, first convert your css files to scss

styles.desktop.scss

@media (min-width: 940px) {
   // your styles here
}

styles.mobile.scss

@media (max-width: 940px) and (min-width: 100px) {
  // mobile specific styles here
}

Edit you .angular-cli.json

Add both scss to app.styles

"apps": [
  {
    ...
    styles: [
      "styles.desktop.css",
      "styles.mobile.css"
    ]
  }
]

ng build --prod should automatically produce a hashed and a stylesheet file.

1 Comment

Thanks for your response but mobile user will end up downloading desktop css which is never gonna used and vice-versa

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.