4

In Drupal 8 some javascript changes were introduced so now all js scripts should be defined using hook_library_info() and added to the page only with #attached attribute of the render array.

But what best practices are recommended to define external libraries? Should we create /libraries directory and upload library there? Or should they be managed by the module using composer?

So how should be the javascript library defined in hook_library_info() in Drupal 8?

  • 1
    I don't think this is actually a D8 question. The approach hasn't changed, even in D7 you should define your libraries and use #attached. Providing optional support for the Libraries module is still a good idea. – tim.plunkett Oct 29 '13 at 22:52
2

Since you posted this question, hook_library_info was replaced with *.libraries.yml files.

An example of a simple library declaration looks like this:

jquery.form:
  remote: https://github.com/malsup/form
  version: 3.39
  js:
    assets/vendor/jquery-form/jquery.form.js: {}
  dependencies:
    - core/jquery
    - core/jquery.cookie

Once declared, this library can be attached to a render array like this:

$element['#attached']['library'][] = 'core/jquery.form';

Now Drupal should take care of adding the library and all required dependencies to the page. Even though the library declaration can contain a remote url, Drupal will not automatically download the library for you.

If I'm not mistaken, you will always need a module or a theme with a .libraries.yml file to act as the provider of your library. However a module can be really simple, you only need a .info.yml file to declare a module.

  • 1
    The last bit's not totally true, you can also use it in a theme... – Clive Apr 3 '14 at 21:45
  • 1
    Thanks Clive, you're completely right. It was so obvious to me that I forgot to mention it :-) I updated the answer. – marcvangend Apr 3 '14 at 22:03
  • 1
    I used this answer to draft documentation on drupal.org: drupal.org/node/2216195 – batigolix Oct 9 '14 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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