Adding an external JavaScript to all pages in Drupal 8

library books

To add a JavaScript library to all pages of your Drupal 8 site, you can either add it to your theme or create a module.

This tutorial will demonstrate how one can do it with a module. One reason to do so is to add functionality to your site independent of the theme.

Throughout this tutorial, we will use "myLibrariesLoader" as the module name - replace this with any name you want.

1. Create a myLibrariesLoader folder in the /modules folder. All other steps will be happening inside this folder.

2. Create a file to describe your module

name: my Libraries Loader
description: A module to install my libraries on D8.
package: Custom
type: module
version: 1.0
core: 8.x

3. Create a myLibrariesLoader.libraries.yml file with your libraries, add header:true if you have a good reason to want the library to load in the <head> section of the pages.

  version: 1.x
  header: true
  js: { external: true, attributes: { defer: true, async: true, data-if-needed: 53952d } }

  version: 1.x
  js: { external: true, attributes: { defer: true, async: true } }

4. Create a myLibrariesLoader.module file to attach your libraries:


 * Implements hook_page_attachments().
 * @param array $attachments
function myLibrariesLoader_page_attachments(array &$attachments) {
    //add here any conditions if you need to limit the pages

    $attachments['#attached']['library'][] = 'myLibrariesLoader/library_one';
    $attachments['#attached']['library'][] = 'myLibrariesLoader/library_two';

6. Check your myLibrariesLoader folder, you should have the following files:

7. Go to the Extend menu and install your my Libraries Loader module by ticking its box and saving (it should appear in the list)

When you inspect your pages, you should now see the following:

<script src="" defer async data-if-needed="53952d"></script>
<script src="" defer async></script>

You can download this sample module here: myLibrariesLoader on GitHub