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
- Removed
<script>
and</script>
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 </body>
- 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';
}
- Cleared cache.
{ preprocess: false }
property, the script does not get aggregated: drupal.org/docs/8/theming/…