Add JavaScript and CSS to a single Drupal page

Submitted by Erik Wegner on
Body

For plotting a graph I would like to use the JavaScript library jqPlot. Adding it to Drupal 8 requires some steps, if the library is not needed on all pages:

  1. Define a module
  2. Define a library
  3. Define a hook

Define a module

Create a folder with the name of your module. Add an info file to it:

name: EWUS
type: module
core: 8.x
package: Other
version: 8.x-1.0

Define a library

To let Drupal know about jqPlot, we define a library. This library depends on jquery.

jqplot:
  css:
    theme:
      css/jquery.jqplot.css: {}
  js:
    js/blogstatistik.js: {}
  dependencies:
    - core/jquery

Define a hook

A hook is one way to extend Drupal. At its core it is a function with a special name. The function here is an implementation of hook_page_attachments. It checks if the current address points to the node where jqPlot is used:

<?php

function ewus_page_attachments(array &$page) {
  /* /node/444 uses the jqPlot library */
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node !== NULL && $node->id() == 444) {
    $page['#attached']['library'][] = 'ewus/jqplot';
  }
}