Include JavaScript and CSS Files for a Single Page in Drupal 8

Here’s how to include JavaScript and CSS files for a single node on your Drupal 8 site, without having them load on every page.

In this example, we’re adding the CSS and JavaScript files for JQVMap to draw a map of the United States on node 13. We’re using a theme called Example, but you’d want to swap out example for your theme’s project name everywhere you see it in the code.

Copy your .css and .js files into a folder within /themes/example/includes/

Add this to /themes/example/example.libraries.yml:

jqvm:
  css:
    theme:
      includes/jqvmap/jqvmap.css: {}
  js:
    includes/jqvmap/jquery.vmap.js: {}
    includes/jqvmap/maps/jquery.vmap.usa.js: {}
  dependencies:
    - core/jquery

Add this to /themes/example/example.theme:

function example_preprocess_page(&$variables) {
	$node = \Drupal::request()->attributes->get('node');
	if (!empty($node)) { $nid = $node->id(); } else { $nid = null; }
	if ($nid == 13) {
		$variables['#attached']['library'][] = 'example/jqvm';
	}
}

Flush site cache from this admin page:
/admin/config/development/performance

And then go back to view node 13 and you should see it pulling in the JQVMap files.

(If this feels like too much work for you, there’s a hack that’ll let you add jQuery code within the body of a Drupal 8 page.)


Comments

Loading…

This post was published on September 14th, 2018 by Robert James Reese in the following categories: CSS, Drupal, JavaScript, and jQuery Before using any of the code or other content in this post, you must read and agree to our terms of use.