javascriptdrupaldrupal-8drupal-theming

Add js script to drupal


I have the following that i need to add to all drupal pages of a website:

<script type="text/javascript">
var __cs = __cs || [];
__cs.push(["setCsAccount", "code"]);
</script>
<script type="text/javascript" async src="https://...cs.min.js"></script>

I tried to add it to one of the themes i have as a library by using

(function ($) {
    Drupal.behaviors.myModuleBehavior = {
        attach: function (contect, settings) {
            document.write('<script type="text/javascript">...</script>');
        }
    }
})

But nothing happened, there is another theme in the website with the following files enter image description here

I'm not sure I'm going on at it in the correct way since i'm new to drupal but the most important thing to me is that i prefer not to add any modules or outside libraries to the website


Solution

  • Override the html.html.twig of whatever theme your theme is inheriting from and just put your javascript in the head section.

    1. find what theme your theme is inheriting from, it will say in your themes .info.yml file, look for "base theme". For example HERE you can see that the classy theme is inheriting from the stable theme.
    2. Copy the html.html.twig file from your base theme and put it in your theme, keeping the directory structure is probably a good idea, but not absolutely necessary. If you can't find the file in your base theme, or your theme does not have a base theme, you could just use the html.html.twig from one of the core themes, eg the stable themes html.html.twig file.
    3. Add your javascript to the head section of your html.html.twig file. Add the first code that you posted, probably no need for drupal behaviors.