I've added some scripts in head tag using

<referenceBlock name="head.additional">
     <block class="Magento\Framework\View\Element\Template" name="custom_script_block" template="Magento_Theme::script/code.phtml"/>

All the scripts have moved at the end of page after . But the html comments are in the head tag which has in the code.phtml

Anyone knows it why?


Create default_head_blocks.xml in your theme :


<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <script src="https://www.google.com/recaptcha/api.js" src_type="url"/>
  • I need to add it in within <head> tag. – JAY May 30 '18 at 7:25
  • Do you want to add js in all pages ? are you used javascript link or added js in folder ? – hweb87 May 30 '18 at 7:27
  • Yes exactly. I need to add gtag code in head tag. But it's moving to end. You can see it here bit.ly/2H3e713 – JAY May 30 '18 at 7:29
  • I have updated my comment – hweb87 May 30 '18 at 7:53

You can try this code its working for me for gtag:

<referenceBlock name="head.additional">
    <block class="Magento\Framework\View\Element\Text" name="ga_script">
        <action method="setText">
            <argument translate="true" name="text" xsi:type="string">
                    <script type='text/javascript'>
                    window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_TRACKING_ID');

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.