Skip to main content

How to include a third-party JS file in a custom block

Front-end Development
Drupal

One great aspect of Drupal is how flexible and extendable it is. For many users, this comes in the form of installing community contributed and maintained modules that provide functionality beyond what you get out of the box with Drupal core.

Sometimes, however, site builders and developers need to add functionality or create features that are not provided in Drupal core or a contributed module, but perhaps can be provided by a third-party JS library or file. This is where that extendability comes to the rescue.

The basic concept

With the above in mind, let’s say you have a piece of functionality you wish to implement on a Drupal site that you have made the following determinations about: 

  1. It can't be provided by Drupal core or a contributed module
  2. It requires leveraging a third-party JS library/file to achieve the functionality you desire
  3. You will be using said JS in a component that will be placed on a page or number of pages via a custom block

You’ll need a custom block. To make it, you'll first have to create a simple custom module. This article assumes you already know the basics of creating a custom module, but if you don't, Drupal's documentation has some good guides:

Once you have your module and block in place, you can use a property called attached to, well, attach a file or library to the block, which can include, but isn't limited to, JS. 

Making the magic happen

Drupal 7

Create a simple custom module. For the sake of the following examples, it's called myblock. Inside the module, create a js directory to hold the file(s) for the third-party JS code, in this example, it's called file.js.

In the custom module's .module file, define and create the contents for a block (note the #attached array):

<?php

// Define the block.
function myblock_block_info() {
  $blocks['myblock-blockname'] = [
    'info' => t('Administrative block title'),
    'cache' => DRUPAL_NO_CACHE,
  ];
  return $blocks;
}

// Define the block's content.
function myblock_block_view($delta = '') {
  $block = [];
  switch ($delta) {
    case 'myblock-blockname':
      $block['subject'] = t('Block Title');
      $block['content'] = [
        // Attach our third party JS, contained in the module's js directory.
        '#attached' => [
          'js' => [
            drupal_get_path('module', 'my_module') . '/js/file.js',
          ],
        ],
        'container' => [
          '#type' => 'html_tag',
          '#tag' => 'div',
          '#attributes' => [
            'class' => ['my-class'],
          ],
          '#value' => '',
        ],
      ];
      break;
  }
  return $block;
}

Drupal 8/9

Create a simple custom module. Define the external JS library in a .libraries.yml file within your custom module's directory. This can work with external libraries that are installed on your project via a package manager like composer or npm, or it can be done like in the D7 example above with individual files that you manually add to your custom module. The following examples also assume that jQuery is a dependency of the external JS you will be adding. 

Third-party JS, installed via a package manager

myblock:
  version: 1.x
  dependencies:
    - core/jquery
    - library_name/component

Third-party JS, installed via adding the file to your custom module in a directory named 'js':

myblock:
  version: 1.x
  js:
    js/file.js: {}
  dependencies:
    - core/jquery

Then define the block itself in the myblock.module file:

<?php

namespace Drupal\myblock\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a Block.
 *
 * @Block(
 *   id = "block_name",
 *   admin_label = @Translation("label"),
 *   category = @Translation("category"),
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      // This can be a simple bit of markup or a complex render array!
      '#type' => 'html_tag',
      '#tag' => 'div',
      '#attributes' => [
        'class' => [
          'my-class',
        ],
      ],
      // Attach our third party JS, as defined in the module's libraries.yml file.
      '#attached' => ['library' => ['library_name/component']],
    ];
  }

}

Next steps

Now that you have the block made, you can place it on a page or pages from the Drupal block admin to see the results! It probably won't look like much, or anything yet, but the foundation is in place and you should be able to see the block's markup in your inspector and the attached JS file(s) in the footer of the page's source and work from there to implement your custom feature.

As you can see in the above examples, the actual implementation may be different between D7 vs D8/9, but the basic concept is the same: create a module that outputs a custom block, then define a library or add a third-party JS file to your module and then attach it to your block with the #attached property.

Need a fresh perspective on a tough project?

Let’s talk about how RDG can help.

Contact Us