I am developing a custom module in Drupal 8. My custom module include many JavaScript and CSS files which make the site really slow and I don't want them in all pages. I have developed some custom blocks and each JavaScript and CSS library correspond to a block. I want those files on those pages of the site where my custom blocks are visible.

In my last Drupal 8 project, I have done something like the following.

function HOOK_page_attachments(array &$attachments) {
    $user = \Drupal::currentUser()->getRoles();

    if(in_array("administrator", $user)){
        $attachments['#attached']['library'][] = 'module/library';

I am not sure how to check which blocks are visible in the page.

  • 2
    They should be attachments to the block content itself, surely? – Clive May 30 '17 at 13:06

You have to attach the library to block content, hopefully code below should help

| improve this answer | |

If you're using a twig template, you can add it there.

{{ attach_library('module/library') }}

Which is helpful when you want to control whether the library loads before or after the content.


| improve this answer | |

Resolving this doubt: I am not sure how to check which blocks are visible in the page.

block.module have a service that you can invoke:



I think that you can use it to resolve your case.

And in other hands is not the best practice check the use role, maybe will be better check the permissions that you want to check. If you want in the future, that another role can see the block, you cannot do it without grant the administrator role to this user.

| improve this answer | |

Your Answer

