Score:0

How can I add an external/third party library with type = 'module' using drupal_add_js()?

mp flag
  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.

Ivaylo Tsandev avatar
us flag
Have you tried with `type => file` as per the documentation here https://www.drupal.org/docs/7/api/javascript-api/adding-javascript-to-your-theme-or-module#s-with-drupal-add-js
Score:0
us flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.