5

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.

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

3 Answers 3

5

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

$build['#attached']['library'][] = 'module/library';
1
  • 2
    How is adding to a block, adding to a specific page?
    – liquidcms
    Commented Oct 21, 2020 at 19:14
7

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.

https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

-1

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:

getVisibleBlocksPerRegion()

https://api.drupal.org/api/drupal/core%21modules%21block%21src%21BlockRepository.php/function/BlockRepository%3A%3AgetVisibleBlocksPerRegion/8.2.x

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.

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.