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 myLibrariesLoader.info.yml 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.

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

library_two:
  version: 1.x
  js:
    https://external.url2.org/library.js: { external: true, attributes: { defer: true, async: true } }

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

<?php

/**
 * 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:

myLibrariesLoader.info.yml
myLibrariesLoader.libraries.yml
myLibrariesLoader.module

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="https://external.url.com/" defer async data-if-needed="53952d"></script>
<script src="https://external.url2.org/library.js" defer async></script>

You can download this sample module here: myLibrariesLoader on GitHub