Add inline JavaScript to end of page dynamically Use case:

I have a custom block:

/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "my",
 *   admin_label = @Translation("My Block"),
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $build = array(
      '#markup' =&gt; 'SOME WEIRD ADS HTML HERE'
    );

    SOME_COOL_STUFF_TO_ADD_INLINE_JAVASCRIPT_TO_THE_CLOSING_BODY_TAG

    return $build;
  }
}


Is there a way to add inline javascript to the end of the page just when this block is rendered anywhere (in theme or panel page)?
You just use the following code.

$build = [
  '#markup' =&gt; 'SOME WEIRD ADS HTML HERE',
  '#attached' =&gt; [
    'library' =&gt; ['mymodule/mylibrary'],
  ],
];


Follow Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module to learn how to define a library for Drupal 8, and keep in mind that, by default, JavaScript files are added to the footer, as explained in LibraryDiscoveryParser::parseLibraryInfo().


  By default, JavaScript files are included in the footer.


Also, #markup is filtered out, as explained in Render API overview.


  #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (For example, &lt;script&gt; and &lt;style&gt; are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed_tags to alter which tags are filtered.