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

3 Answers 3

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
    – Chetan
    Jun 1, 2019 at 11:19
  • Which one did u use @Sam?
    – aravind
    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. May 15, 2020 at 8:53
  • @CodeForGood You need to add the code in default.xml to display in all the pages
    – aravind
    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. May 15, 2020 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>
0

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

1

Your Answer

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

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