How can I disable all the JavaScript scripts? I am trying to disable all the JavaScript on all the pages of a Drupal 8 site for anonymous users if there is a particular header in the request object.
I tried out this code.
/**
 * Implements hook_js_alter().
 */
function MODULE_js_alter(&amp;$javascript, AttachedAssetsInterface $assets) {
  if (MODULE_get_headers()) {
    unset($javascript);
  }
}

/**
 * Implements hook_page_attachments_alter().
 */
function MODULE_page_attachments_alter(&amp;$attachments) {
  // This is for disabling all 3rd party libraries. 
  if (MODULE_get_headers()) {
    $attachments['#attached']['library'] = [];
  }
}

It does seem to work to a certain extent. It disables most of JavaScript, but I am seeing the styles are also off (which might be expected) as the CSS libraries might also be removed.
Is there a better way to do this? Maybe Drupal has an option to turn off all the JavaScript.
You don't necessarily need to turn off aggregation if you want to remove all javascript. You could for example remove the placeholder in the html template, then the (already aggregated) javascript won't be replaced in the html page:
function mymodule_preprocess_html(&amp;$variables) {
  if (MODULE_get_headers()) {
    unset($variables['#attached']['html_response_attachment_placeholders']['scripts']);
    unset($variables['#attached']['html_response_attachment_placeholders']['scripts_bottom']);
  }
  $variables['#cache']['contexts'][] = 'headers:my-header';
}

You need a cache context for the request header. This doesn't work for the Internal Page Cache, though. So you need to uninstall this module or extend it to add the request header to the cache key.