2

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

Vendor provided some JS in the following form:

<script>
    ... code
</script>

Asked me to place immediately above </body>.

The script was only to run for Anonymous traffic.

Here's how I did it:

THEME = name of your theme

  1. Removed <script> and </script> from code
  2. Minified using https://javascript-minifier.com/
  3. Created file name-of-my-script.min.js
  4. Uploaded to THEME/js/custom/name-of-my-script.min.js
  5. 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 </body>
  1. Added the following code to THEME.theme to an already existing function: function THEME_preprocess_page(&$variables) {}
$logged_in = $variables['logged_in'];
    if (!$logged_in) {
    $variables['#attached']['library'][] = 'THEME/name-of-my-library';
}
  1. Cleared cache.

Resourses that helped:

9
  • I see that I need to escape the closing body tag. I don't have edit access (even though I created post) so could admin please help with that? Tahnks. Sep 13, 2019 at 16:27
  • Your script get's aggregated by Drupal's core. You will not see it in the rendered page output. You may change the aggregation on /admin/config/development/performance. Sep 13, 2019 at 16:30
  • By adding { preprocess: false } property, the script does not get aggregated: drupal.org/docs/8/theming/… Sep 13, 2019 at 16:50
  • What is your question - does your code solve the problem?
    – user78966
    Sep 14, 2019 at 19:46
  • 1
    Please don't add the answer to the question. Please add it as answer below.
    – leymannx
    Sep 17, 2019 at 16:09

1 Answer 1

0

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('<script src="/name-of-your-library"></script>');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.