5 Ways to Include JavaScript in Drupal 9 for Enhanced Functionality

In this article, we are going to see how to include Javascript in Drupal and there are 5 Ways to Include JavaScript in Drupal 9 for Enhanced Functionality

Adding JavaScript directly in a module or theme file

    • You can include JavaScript code directly in your custom module or theme files using <script> tags. However, it’s generally recommended to use the methods below for better organization and performance.
// Example: Adding JavaScript directly in a custom module file.
// File: mymodule.module

/**
 * Implements hook_page_attachments_alter().
 */
function mymodule_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['html_head'][] = [
    [
      '#tag' => 'script',
      '#attributes' => [
        'src' => 'https://example.com/my-script.js',
      ],
    ],
    'my_script',
  ];
}

 

Adding JavaScript using the .info.yml file:

    • In your custom module or theme’s .info.yml file, you can specify JavaScript files to be loaded using the libraries key. Create a library definition in a separate YAML file and reference it in the .info.yml file. This approach allows you to manage dependencies and define settings for your JavaScript.
# Example: Adding JavaScript using the .info.yml file.
# File: mytheme.info.yml

libraries:
  - mytheme/global-scripts
# Example: Defining the library in a separate YAML file.
# File: mytheme.libraries.yml

global-scripts:
  version: 1.x
  js:
    js/global-script.js: {}

 

Adding JavaScript using the Drupal.behaviors object

    • Drupal.behaviors is a JavaScript object that allows you to attach JavaScript behaviors to elements on a page. You can define your custom behavior in a JavaScript file and use the attach method to apply it to specific elements or classes. This method ensures that your JavaScript is executed after the page has finished loading and any necessary dependencies are resolved.
// Example: Adding JavaScript using Drupal.behaviors.
// File: mymodule.js

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      // Your JavaScript code here.
      $('.my-element').once('myModuleBehavior').on('click', function () {
        // Handle the click event.
      });
    }
  };
})(jQuery, Drupal);

 

Using the #attached property in render arrays

    • When building custom modules or themes, you can use render arrays to define the structure and content of a page. The #attached property of a render array allows you to attach JavaScript files or settings to the rendered output. This method is useful when you want to conditionally load JavaScript based on certain conditions.
// Example: Adding JavaScript using the #attached property.
// File: mymodule.module

/**
 * Implements hook_preprocess_HOOK() for a specific template.
 */
function mymodule_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'mymodule/custom-script';
}
# Example: Defining the library in a separate YAML file.
# File: mymodule.libraries.yml

custom-script:
  version: 1.x
  js:
    js/custom-script.js: {}

 

Adding JavaScript using a preprocess function

    • If you need to add JavaScript to a specific template or theme, you can use preprocess functions. By implementing a preprocess function in your custom module or theme, you can manipulate variables passed to a template and include JavaScript files using the #attached property.
// Example: Adding JavaScript using a preprocess function.
// File: mytheme.theme

/**
 * Implements hook_preprocess_HOOK() for a specific template.
 */
function mytheme_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'mytheme/custom-script';
}
# Example: Defining the library in a separate YAML file.
# File: mytheme.libraries.yml

custom-script:
  version: 1.x
  js:
    js/custom-script.js: {}

 

Using contributed modules

    • Drupal has several contributed modules that provide additional functionality for managing and including JavaScript files, such as the Asset Injector module or the Libraries module. These modules offer more advanced features and configurations for including JavaScript on your site.

Remember to clear Drupal’s cache after making changes to JavaScript files or their inclusion methods to ensure the changes take effect.

1 thought on “5 Ways to Include JavaScript in Drupal 9 for Enhanced Functionality”

Leave a Comment