Add third-party JavaScript as for tracking codes in a way that does not slow down the site

There’s no really good set play for this, sticking some horrible bit of spying code your client’s marketing-oriented shot-callers insist be stuck on your beautiful pure website. There’s especially no set way to add inline JavaScript, async external JavaScript, and a non-JS fallback all in one go. Instead there is a lot of documentation to wade through, that doesn’t give you all you need in one place.

Two modules are pretty well on their way to fixing this:

https://www.drupal.org/project/add_to_head

https://www.drupal.org/project/header_and_footer_scripts

But for the moment i went custom.

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal module | Creating custom modules | Drupal Wiki guide on Drupal.org

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_page_bottom/9.3.x

Here we need to add some unpleasant LinkedIn spyware on an otherwise lovely government website.

I threw it in a custom module we already had, so this is in file vhfa_nav.module:

<?php
/**
 * Implements hook_page_bottom().
 */
function vhfa_nav_page_bottom(array &$page) {
  if (!vhfa_nav_track_here()) {
    return;
  }

  $page['vhfa_linkedin_tracking_js'] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => '_linkedin_partner_id = "1158641";
      window._linkedin_data_partner_ids = window._linkedin_data_partner_ids || [];
      window._linkedin_data_partner_ids.push(_linkedin_partner_id);'
    ],
  ];
  $page['vhfa_linkedin_tracking_pixel'] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'noscript',
      '#value' => '<img height="1" width="1" style="display:none;" alt="" src="https://dc.ads.linkedin.com/collect/?pid=1158641&fmt=gif" />',
    ],
  ];
}

/**
 * Implements hook_page_attachments().
 */
function vhfa_nav_page_attachments(array &$page) {
  if (!vhfa_nav_track_here()) {
    return;
  }

  $page['#attached']['library'][] = 'vhfa_nav/linkedin-analytics';
}

/**
 * Return true if the tracking should be done for current user and page.
 */
function vhfa_nav_track_here() {
  if (\Drupal::currentUser()->hasPermission('access administration pages')) {
    return FALSE;
  }
  return TRUE;
}

And that attached library, defined in vhfa_nav.libraries.yml:

linkedin-analytics:
  js:
    https://snap.licdn.com/li.lms-analytics/insight.min.js: { type: external, minified: true, attributes: { defer: true, async: true } }