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: