0

This question already has an answer here:

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(&$vars) {
  $uuid = trim(variable_get('variable_id', ''));
  drupal_add_js('//cdn.cookielaw.org/consent/'.$uuid.'.js', array(
    'type' => 'external',
    'scope' => 'header',
    'group' => JS_THEME,
    'every_page' => TRUE,
    'weight' => -1,
  ));
}

What function/method should I use in Drupal 8?

marked as duplicate by kiamlaluno Mar 5 '18 at 13:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

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';

Not the answer you're looking for? Browse other questions tagged or ask your own question.