Magento – Add inline javascript to head – magento2

default.xmlheadjavascriptmagento2

I am struggling to load a script tag on my Magento website. I am trying to add this to the head by adding the below code. I have tried to add this to the default.xml and default_head_blocks.xml

    <!-- Bugherd -->
    <reference name="head.additional">
        <block type="Magento\Framework\View\Element\Text" name="my_script">
            <action method="setText">
                <argument translate="true" name="text" xsi:type="string">
                    <![CDATA[
                        <script type='text/javascript'>
                        (function (d, t) {
                          var bh = d.createElement(t), s = d.getElementsByTagName(t)[0];
                          bh.type = 'text/javascript';
                          bh.src = 'https://www.bugherd.com/sidebarv2.js?apikey=dkjfsd89id6sftsdghkjn3';
                          s.parentNode.insertBefore(bh, s);
                          })(document, 'script');
                        </script>
                    ]]>
                 </argument>
            </action>
         </block>
    </reference>

Error:

1 exception(s):
Exception #0 (Magento\Framework\Config\Dom\ValidationException): Element 'reference': This element is not expected. Expected is one of ( attribute, block, referenceBlock, referenceContainer, container, move, uiComponent ).
Line: 637

Can anyone please advise how I can add my script to the head across all pages?

Thanks

Best Answer

I would advise using Require JS to load this rather than adding it via XML like this, but if you're adamant you want to do it this way try this:

<!-- Bugherd -->
<referenceBlock name="head.additional">
    <block class="Magento\Framework\View\Element\Text" name="my_script">
        <action method="setText">
            <argument translate="true" name="text" xsi:type="string">
                <![CDATA[
                    <script type='text/javascript'>
                    (function (d, t) {
                      var bh = d.createElement(t), s = d.getElementsByTagName(t)[0];
                      bh.type = 'text/javascript';
                      bh.src = 'https://www.bugherd.com/sidebarv2.js?apikey=dkjfsd89id6sftsdghkjn3';
                      s.parentNode.insertBefore(bh, s);
                      })(document, 'script');
                    </script>
                ]]>
             </argument>
        </action>
     </block>
</referenceBlock>

Same as mtr.web's answer but uses class rather than block.