9

How do I force a JavaScript library to load in the < head > in Drupal 8?

Here's my themename.libraries.yml file:

zaccordion:
  version: 1.x
  js:
    js/jquery.zaccordion.js: { header: true }
    js/jquery.zaccordion.min.js: { header: true }
    js/zaccordionUsage.js: { header: true }
  dependencies:
    - core/jquery

It still loads in the footer however.

1 Answer 1

13

header: true needs to go under your js declaration, not within each file.

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

By default, all JS assets are now loaded in the footer. Being loaded in the header is now an opt-in choice, that is only necessary for critical UI elements that cannot be shown unless their corresponding JS has already run.

js-header:
  header: true
  js:
    header.js: {}

js-footer:
  js:
    footer.js: {}

You have to set the new header property on asset library definitions to true, to indicate that the JavaScript assets in that asset library are in the critical path, and should therefore be loaded from the header. Note that any dependencies — direct and indirect — of asset libraries marked as being in the critical path are also automatically loaded from the header, so you don't need to worry about dependencies being unavailable.

0

Your Answer

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

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