5

I want to add js before body end tag in magento 2

i am trying this code

<body>
    <referenceContainer name="before_body_end">
        <script src="ABC_Example::js/jquery.js" />
        <script src="ABC_Example::js/custom.js"/>
    </referenceContainer>
</body>

but its not working

2
16

I don't think it's possible to use <script> or <link> within the layout XML <body> tag, same as you can't use <block> or <container> within the layout XML <head> tag.

The closest way to do this with only XML (that I'm aware) is to use text, like so:

<referenceContainer name="before.body.end">
    <block class="Magento\Framework\View\Element\Text" name="exampleScript">
        <arguments>
            <argument name="text" xsi:type="string"><![CDATA[<script type="text/javascript" src="//www.example.com/example-script.js"></script>]]></argument>
        </arguments>
    </block>
</referenceContainer>
2
  • there is one question this for external link but i want to add my module file like this 'ABC_Example::js/custom.js' using that i am getting 404 error
    – Newbie
    Mar 7 '16 at 6:45
  • You would need to edit your path to match your file, something along the lines of /pub/static/frontend/STORE_NAME/THEME_NAME/en_US/ABC_Example/js/custom.js - If you struggle to find the URL just add it normally via the <script> or <link> tag within the XMLs head, then copy that URL. There must be an easier way to add local JS elsewhere, maybe extending the <head> functionality if that's possible or editing <body> to allow <script> but that's beyond my knowledge.
    – Ben Crook
    Mar 7 '16 at 8:41
9

You can achieve this using template call

<referenceContainer name="before.body.end">
        <block class="Magento\Framework\View\Element\Template" template="Namespace_Modulename::before.phtml" name="before_body_js"/>
</referenceContainer>

add template file before.phtml add below code

<script src="your js path" />
4
  • there is no phtml i want to just add js
    – Newbie
    Mar 4 '16 at 11:09
  • I believe @PrashantValanda means place the <script src="your js path" /> inside the before.phtml file, which then is called from the referenceContainer block to output Oct 11 '17 at 15:16
  • class="\Magento\Framework... should be class="Magento\Framework
    – Joel Davey
    Sep 21 '18 at 10:46
  • @JoelDavey yes you right Sep 23 '18 at 7:23
6

I didn't understand why you need to make any code-level change as Magento 2 has this functionality by default to add anything in head or body tag

Admin >> content >> design >> configuration >> Select Store >> html HEAD/Footer (Miscellaneous HTML) enter image description here

Edit: This would make the script available on every page on the site, if you want it to be available specifically, you can make use of layout as described in other answers.

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