Skip to main content

Add custom js into <head> programmatically Drupal 8

you can download and use this module Header and Footer Scripts

/**
* Implements hook_page_attachments_alter().
*
* Alter attachments (typically assets) to a page before it is rendered.
*/
function MY-MODULE-NAME_page_attachments_alter(array &$attachments) {
 
  $attachments['#attached']['html_head'][] = [
  [
  ' '#type'  => 'html_tag',
    '#tag'   => 'script',
    '#value' => '<script type="text/javascript">console.log("HFS Header3");</script>',
  ], 'MY-MODULE-NAME'
  ];
}