How do I add a script just above the closing body tag? How do I add a script on Drupal 8 site/app just above closing body tag?

Vendor provided some JS in the following form:

&lt;script&gt;
    ... code
&lt;/script&gt;


Asked me to place immediately above &lt;/body&gt;.

The script was only to run for Anonymous traffic.

Here's how I did it:

THEME = name of your theme


Removed &lt;script&gt; and &lt;/script&gt; from code
Minified using https://javascript-minifier.com/
Created file name-of-my-script.min.js
Uploaded to THEME/js/custom/name-of-my-script.min.js
Added library to bottom of THEME.libraries.yml


name-of-my-library:
  version: 1.0
  js:
    js/custom/name-of-my-script.min.js: {preprocess: false} // {preprocess: false} is responsible for code showing up above &lt;/body&gt;



Added the following code to THEME.theme to an already existing function: function THEME_preprocess_page(&amp;$variables) {}


$logged_in = $variables['logged_in'];
    if (!$logged_in) {
    $variables['#attached']['library'][] = 'THEME/name-of-my-library';
}



Cleared cache.


Resourses that helped:


https://www.drupal.org/docs/8/api/javascript-api/add-javascript-to-your-theme-or-module
https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module
You can achieve this simply by using jquery. If you want to access it from all theme pages you need to add the below line in your global common js file which has access to all the theme pages in the app.

$('body').append('&lt;script src="/name-of-your-library"&gt;&lt;/script&gt;');