0

I'd like to exclude a js file from loading on to a specific node.

Right now my libraries.yml file looks like this:

global-styling:
  version: 1.x
  css:
    theme:
      css/bootstrap/bootstrap.css: {}
      css/style2.css: {}
      css/header.css: {}
      css/color-1.css: {}
      css/themify-icons.css: {}
      css/jquery-ui.css: {}
  js:
    js/bootstrap.js: {}
    js/jquery-ui.js: {}
    js/popper.js: {}
    js/tooltip.js: {}
    js/wow.min.js: {}
    plugin/appear/jquery.appear.js: {}
    js/custom.js: {}
  dependencies:
    - core/jquery

I'd like to exclude the js/custom.js from loading on node/4. Alternatively I would like to load that file ONLY for the front page.

2 Answers 2

4

Delete/Exclude js/custom.js from the global-styling section in THEMENAME.libraries.yml and define it as a library at the end of the same file

# THEMENAME.libraries.yml
custom-js:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery

And then include the library conditionally to where you want it using THEMENAME_preprocess_page function in THEMENAME.theme

//THEMENAME.theme
function THEMENAME_preprocess_page(&$variables) {

    //include it if its front_page
    if ($variables['is_front'] == TRUE) {
        $variables['#attached']['library'][] = 'THEMENAME/custom-js';
    }

    //include it if its NOT node 4
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface && $node->id() != 4) {
        $variables['#attached']['library'][] = 'THEMENAME/custom-js';
    }  
}       

For more info read the docs

2

If you want to load the file only for the front page, separate that file to another library like:

global-custom-styling:
  js:
    js/custom.js: {}

And preprocess page then attach library:

function mytheme_preprocess_page(&$variables){
  if ($variables['is_front'] == TRUE) {
    $variables['#attached']['library'][] = 'my-theme/global-custom-styling';
  }
}

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.