Inline JS

Component ID

2392465

Component name

Inline JS

Component type

module

Maintenance status

Development status

Component security advisory coverage

covered

Downloads

1032

Component created

Component changed

Component body

Allows to add inline JavaScript code to different part/position of JS script tag as there is no straight forward way in Drupal 8 core.

How to install

  1. Install module as usual
  2. Add below code to sites/default/services.yml
    services:
      asset.js.collection_renderer:
        class: DrupalinlinejsAssetInlineJsCollectionRenderer
        arguments: [ '@state' ]
    
  3. Implement hook_inlinejs_alter() to add your JS snippet.
    /**
     * Implements hook_inlinejs_alter().
     */
    function MODULENAME_inlinejs_alter() {
      $js_asset['header'][] = array(
        'data' => 'alert("header before");',
        'group' => JS_LIBRARY - 1,
      );
      $js_asset['header'][] = array(
        'data' => 'alert("header after");',
        'group' => JS_LIBRARY + 1,
      );
      $js_asset['footer'][] = array(
        'data' => 'alert("footer before");',
        'group' => JS_LIBRARY - 1,
      );
      $js_asset['footer'][] = array(
        'data' => 'alert("footer after");',
        'group' => JS_LIBRARY + 1,
      );
      return $js_asset;
    }