Experimental project

This is a sandbox project, which contains experimental code for developer use only.

This module makes the function drupal_add_js() available to Drupal 8 websites.

How to use:

Download and enable the module, then call drupal_add_js in your custom module or theme like so:

function your_module_preprocess_html($vars) {
  drupal_add_js('modules/custom/your_module/script.js');
}

Now script.js will be loaded on every page. You must clear drupal cache (drush cr) when adding, removing, or modifying a call to drupal_add_js(). Optionally, you can control the behavior of your script more granularly with an array of settings, like so:

  $settings = array(
    "weight" => 10,
    "cache" => false,
    "preprocess" => false,
    "scope" => "footer",
  );
  drupal_add_js('modules/custom/your_module/script.js', $settings);

The allowed settings are:

  • group
  • type
  • version
  • minified
  • weight
  • cache
  • preprocess
  • attributes
  • browsers
  • scope

See hook_js_alter() for more information on how to use these settings.

Additional Examples

Add an externally hosted script to every page

function test_module_preprocess_html(&$vars) {
  $settings = array(
    "type" => "external",
  );
  drupal_add_js('http://example.com/script.js', $settings);
}

Add a JS setting to every page

function test_module_preprocess_html(&$vars) {
  $settings = array(
    "type" => "setting",
    "data" => array(
      "show_popups" => false
    )
  );
  drupal_add_js('', $settings);
}

Note, JS settings are not available through the global variable drupalSettings, rather than Drupal.settings.

Why:

In Drupal 7, the function drupal_add_js() was used to add arbitrary javascript to any page. This functionality was removed from core in Drupal 8, in favor of the library system. While the library system is a useful tool for many cases, some of us would like the option to use drupal_add_js occasionally. In particular, I find drupal_add_js useful for rapid prototyping.

Todo:

  • Improve documentation
  • Allow adding of inline scripts
  • Create a separate drupal_add_css() module
Supporting organizations: 

Project information