Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Drupal 8 add inline JavaScript to a page

Parent Feed: 

Separate JS files are good but in certain cases (e.g. tracking scripts) it might be useful to just add a piece of inline code to a specific page.

This can easily be achieved from a custom module by implementing hook_page_attachments(), checking the page you are on and adding the JS code to the HTML head.

Here is the sample code:

  1. /**

  2.  * Implements hook_page_attachments().

  3.  */

  4. function MODULE_NAME_page_attachments(array &$attachments) {
  5.   // You can optionally perform a check to make sure you target a specific page.

  6.   if (\Drupal::routeMatch()->getRouteName() == 'some.route') {

  7.     // Add our JS.

  8.     $attachments['#attached']['html_head'][] = [

  9.       [

  10.         '#tag' => 'script',

  11.         '#attributes' => [

  12.           'type' => 'text/javascript',

  13.         ],

  14.         '#value' => 'console.log("i am here");',

  15.       ],

  16.       'key_for_this_snippet',

  17.     ];

  18.   }

  19. }

See more:

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web