0

I am trying to remove all unnecessary/unused stylesheets for anonymous visitors to get better performance and a clean <head> section. This works fine by listing them inside mytheme.info.yml:

stylesheets-remove:
  - path/to/stylesheet.css
  - path/to/another/stylesheet.css
  - core/modules/system/css/components/hidden.module.css

However, the third entry in this example breaks the styling of the toolbar - which is only visible to the admin. Is it possible to programatically tell Drupal which stylesheets to remove only for anonymous visitors? I appreciate your help!

2 Answers 2

1

Having tried to do this myself before, this is probably not a route you want to go down. This approach becomes harder to maintain as you install more modules (different modules can inject CSS on different paths), and often can turn into a maintenance nightmare.

Drupal can aggregate CSS files out of the box; this is often all you need to improve performance dramatically.

To turn on the basic aggregation, you can check Aggregate CSS files at /admin/config/development/performance.

To do something more complicated, try using the Advagg module. Configuring this module can be complex but it allows you to do more specific aggregation, CSS minification, and so on.

1
  • Yes, I agree that this solution is definitely better for maintainability. I will take a look at the Advagg module as well. Thanks for your help! Commented Jul 16, 2020 at 11:06
-2

you can use hook bellow (check for the right path)

function MYMODULE_page_attachments_alter(array &$attachments) {
  if(\Drupal::currentUser()->isAnonymous()) {
    unset($attachments['#attached']['library']['core/modules/system/css/components/hidden.module.cs']);
  }
}
9
  • 1
    That seems to be the way to go, although I think it has to be $attachments['#attached']['library'][0] in order to remove all the system css stuff. Thanks! Commented Jul 14, 2020 at 17:57
  • 1
    You can only remove libraries but not a single CSS file like that.
    – leymannx
    Commented Jul 14, 2020 at 22:06
  • 1
    You can only remove libraries added by other hook_page_attachments or hook_page_attachments_alter implementations.
    – 4uk4
    Commented Jul 15, 2020 at 6:59
  • 1
    @4k4 – ... or added from a theme's info file.
    – leymannx
    Commented Jul 15, 2020 at 7:41
  • 1
    $attachments['#attached'['library'['core/modules/system/css/components/hidden.module.cs'] contains a syntax error.
    – apaderno
    Commented Jul 15, 2020 at 8:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.