How to attach JavaScript per content type in Drupal 8

Drupal 8 is dramatically different under-the-hood than previous versions. The core is now built with Symfony PHP framework, which adds both sophistication and complexity to Drupal module development.

Drupal 8 introduces a new hook hook_page_attachments used for attaching files to a page. The following module example illustrates how to attach a JavaScript file to a page of a specific content type. (Note: The example does not attempt to thoroughly explain how to create a custom module. Creating a custom module is relatively easy and many how-to tutorials can be found elsewhere.)


custom.info.yml

Let Drupal 8 know about your module with an .info.yml file.

name: Custom
description: Attach a JavaScript file for a page of a specific content type.
package: Custom
type: module
core: 8.x

custom.libraries.yml

Declare the module's dependency on the "custom" library and ensure jQuery is available for js/custom.js.

custom:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

custom.module

Implement hook_page_attachments to determine the type of the content and attach the custom library when applicable.

<?php
/**
 * Implements hook_page_attachments().
 */
function custom_page_attachments(array &$attachments) {
  if (
$node = \Drupal::routeMatch()->getParameter('node')) {
    if (
$node->getType() === 'page') {
     
// Current page is a Page node.
      // Attach JavaScript to the page.
     
$attachments['#attached']['library'][] = 'custom/custom';
    }
  }
}
?>

custom.js

// do something
alert("Hello World");

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.