0
  drupal_add_js('path_to_external_JS_file_on_CDN', [
    'every_page' => TRUE,
    'type' => 'external',
    'defer' => 'defer',
    'attributes' => [
      'async' => true,
      'type' => 'module'
    ],
  ]
);

I tried all combinations of the above, but I couldn't get it work. Is there a way to achieve it using drupal_add_js(), or should I use some other way?

I am trying to achieve this.

<script type='module' src='path_to_external_JS_file_on_CDN'></script>

Edit: I added the code above in my_module_preprocess_page(&$variables). The following code works as expected.

drupal_add_js('path_to_external_JS_file_on_CDN', [
  'every_page' => TRUE,
  'type' => 'external'
]);

I just can't figure out how to load a JavaScript file with the type='module' attribute.

1

1 Answer 1

0

According the function's documentation the module is not an allowed type, that's why it doesn't work.

You may try omitting the type or use the default one - file instead.

The allowed types are 'file', 'inline', 'external' or 'setting'.

The hook you tried my_module_preprocess_page(&$variables) is a good choice.

You may also use the hook_init YOUR_MODULE_NAME_init() in a custom module to ensure your library is loaded everywhere. Please note that hook_init() is triggered after the theme and all modules are loaded already in the memory.

Please check if this solves your issue and put a note with the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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