Add inline JavaScript to end of page dynamically
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.