
Upgrade Your Drupal Skills
We trained 1,000+ Drupal Developers over the last decade.
See Advanced Courses NAH, I know EnoughDrupal 8 add inline JavaScript to a page
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:
/**
* Implements hook_page_attachments().
*/
// You can optionally perform a check to make sure you target a specific page.
if (\Drupal::routeMatch()->getRouteName() == 'some.route') {
// Add our JS.
$attachments['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#attributes' => [
'type' => 'text/javascript',
],
'#value' => 'console.log("i am here");',
],
'key_for_this_snippet',
];
}
}
See more:
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