0

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?

0

1 Answer 1

2

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.