1

I am using Magento 2.3

Can anyone please provide appropriate way for

How can i add my custom script code after the tag.

Thanks

0
6

In your xml add below code,

<referenceContainer name="after.body.start">
    <block name="custom">
        <arguments>
            <argument name="text" xsi:type="string"><![CDATA[<script type="text/javascript" src="js/custom.js"></script>]]></argument>
        </arguments>
    </block>
</referenceContainer>

In case above code not works, you can do it by adding a phtml and declaring script in that phtml.

<referenceContainer name="before.body.end">
        <block template="Namespace_Modulename::custom.phtml" name="meaningful_name"/>
</referenceContainer>

In custom phtml, declare your script,

 <script type="text/javascript">Your script</script>
7
  • This is a correct and proper answer – Sam Jun 1 '19 at 11:19
  • Which one did u use @Sam? – aravind Jun 1 '19 at 11:28
  • @aravind, did you mean default.xml or any other layout xml file by "In your xml add below code". I need to have a script tag right after the body tag for all the pages in the site. Please advice. – CodeForGood May 15 '20 at 8:53
  • @CodeForGood You need to add the code in default.xml to display in all the pages – aravind May 15 '20 at 9:08
  • @aravind, thanks. I just found it out. I shall do it and I hope that this works otherwise I need to try the second solution you offered. – CodeForGood May 15 '20 at 9:09
1

Step 1. Create a custom file custom_body.phtml to add your script code right after body tag.

custom_body.phtml

/app/design/frontend/Vendor/YourTheme/Magento_Theme/templates/html/custom_body.phtml

Write you script code :

<script type="text/javascript">Your script</script>

Step 2. default .xml file: /app/design/frontend/Vendor/YourTheme/Magento_Theme/layout/default.xml add this:

<referenceContainer name="after.body.start">
 <block name="custom.body" before="-" template="Magento_Theme::html/custom_body.phtml" />
</referenceContainer>

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.