I am using Magento 2.3

Can anyone please provide appropriate way for

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



3 Answers 3


In your xml add below code,

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

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"/>

In custom phtml, declare your script,

 <script type="text/javascript">Your script</script>
  • This is a correct and proper answer
    – Chetan
    Commented Jun 1, 2019 at 11:19
  • Which one did u use @Sam?
    – aravind
    Commented Jun 1, 2019 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. Commented May 15, 2020 at 8:53
  • @CodeForGood You need to add the code in default.xml to display in all the pages
    – aravind
    Commented May 15, 2020 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. Commented May 15, 2020 at 9:09

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



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" />

I know this is an old question but what worked for me was adding class="Magento\Framework\View\Element\Text" to aravind's answer


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.