3

We have a custom module that has a JS library that we want to load in the <head> tag as the very first item even before all the normal Drupal JS files. All other libraries are loaded through mytheme.libraries.yml.

How can I load the library (mymodule/myscript) so that it loads as the first <script> tag in the <head>?

What we tried:

mymodule.module

function  mymodule_page_attachments(array &$page) {
  $attachments['#attached']['library'][] = 'mymodule/myscript';
}

mymodule.libraries.yml

myscript:
  version: 1.x
  header: true
  js:
    /path/to/file: { external: true, weight: -200 }

Current problem:

<head>
  <script>script1</script>
  <script>script2</script>
  <script>myscript is loaded here</script>
</head>

Goal:

<head>
  <script>myscript is loaded here</script>
  <script>script1</script>
  <script>script2</script>
</head>
2
  • 1
    You can user hook_page_attachments() in which you can attach your JS library in $page['#attached']['html_head'][]. For more info check this link: Click here
    – Manav
    Commented Jul 12, 2018 at 7:48
  • @Manav the link you shared was able to get me my answer i seeked, I added my answer below. Commented Jul 12, 2018 at 19:39

1 Answer 1

4

Using @Manav's link, i was able to get to this solution that worked.

function mymodule_page_attachments(&$attachments) {
  $custom_script = [
    '#type' => 'html_tag',
    '#tag' => 'script',
    '#attributes' => [
      'src' => 'path/to/file.js',
    ],
    '#weight' => -200, // this allowed me to do what i needed
  ];

  $attachments['#attached']['html_head'][] = [$custom_script, 'custom_script_key'];
}

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.