How do I add an external JavaScript file using a custom module? I am trying to add an external JavaScript file to my site using hook_preprocess_page().

In Drupal 7, I used drupal_add_js().

function mymodule_preprocess_page(&amp;$vars) {
  $uuid = trim(variable_get('variable_id', ''));
  drupal_add_js('//cdn.cookielaw.org/consent/'.$uuid.'.js', array(
    'type' =&gt; 'external',
    'scope' =&gt; 'header',
    'group' =&gt; JS_THEME,
    'every_page' =&gt; TRUE,
    'weight' =&gt; -1,
  ));
}


What function/method should I use in Drupal 8?
Firstly drupal_add_js() removed in Drupal 8, check here.

So create library in your module folder as MODULE_NAME.libraries.yml and in this file if you want to add external js add code like below.

external:
  version: 1.0
  header: true
  js:
      https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js: {type: external, minified: true}


and in any of your module/Form/Controller you can call above library using "#attached"

  $build['#attached']['library'][] = 'MODULE_NAME/external';