You can nudge your life in a new direction every day.

Add script to <head> programmatically in Drupal 8 and 9

Submitted by admin on Sun, 10/25/2020 - 17:41
function my_utlities_page_attachments(array &$page) {

  $page['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => 'console.log("Check the log.");',
      '#weight' => 2,
    ],
    'js_log_script',
  ];
}

A slightly more elegant way might be to separate the array into its own variable 

function my_utlities_page_attachments(array &$page) {

  $js_log = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => 'console.log("Check the log.");',
      '#weight' => 2,
    ],
  ];

  $page['#attached']['html_head'][] = [$js_log, 'js_log_script'];
}