Profile picture for user admin
Daniel Sipos
20 Apr 2015

Drupal 8 comes with many performance improvements, one of which being that javascript is no longer indiscriminately loaded on every page. This means that for anonymous users, there are many pages where there is no jQuery or even javascript loaded.

Although this is a good thing, sometimes you do need jQuery (for example to use Ajax, in which case you'd also need other scripts). So how do you load these files? One way is to use hook_page_attachments() to #attach your own library to the page. However, this is only recommended if the assets you need to attach do not apply to something specific, but to the entire page. The recommended way is to attach the library to a render array because then it will only get loaded if necessary.

And if we look at the documentation page for assets, we'll see how we can add our own library. We need to create a my_module.libraries.yml or my_theme.libraries.yml file. And inside, we can add the following:

my_scripts:
  version: VERSION
  js:
    js/scripts.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Where my_scripts will be the name of the library we will reference when attaching.

As you can see, we are not including any javascript or css of our own, we are just making use of the dependency scripts provided by core. So then what is left to do is to attach this library to a render array (or to the entire page if that is your use case):

$render_array['#attached']['library'][] = 'my_module/my_scripts';

Hope this helps.

Profile picture for user admin

Daniel Sipos

CEO @ Web Omelette

Danny founded WEBOMELETTE in 2012 as a passion project, mostly writing about Drupal problems he faced day to day, as well as about new technologies and things that he thought other developers would find useful. Now he now manages a team of developers and designers, delivering quality products that make businesses successful.

Contact us

Comments

Rich Purple 30 Nov 2015 07:15

New in drupal

Hello ,
I have added libraried in mytheme.info.yml file. but not able to access my css abd js files. Not able to create my custom themes.

nate 29 Mar 2017 22:19

add some custom script so I can use a booking widget

Can you help me understand where I would add this code to my header in Drupal 8. I need to add it so that I can use their booking widget

<script type="text/javascript"> (function() { var co=document.createElement("script"); co.type="text/javascript"; co.async=true; co.src="https://xola.com/checkout.js"; var s=document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(co, s); })(); </script>
Tom 02 May 2019 02:15

saved my bacon!

Thanks for this tip.. you saved my day. I couldn't figure out why my ajax buttons were working for logged-in users but not for anonymous users!

Add new comment