JavaScript – Adding JavaScript Before Closing Body Tag in Magento 1.9

javascriptmagento-1.9

I'm quite new to Magento (ver 1.9.1.0). I'm trying to add a JavaScript just before the closing </body> tag.

I've read other questions about this but none of them seem to work in my situation. Some said that I can edit footer.phtml but I wouldn't want to do that. As much as possible, I want to do it via page.xml located at /app/design/frontend/THEME/PACKAGE/layout

Best Answer

If you want to do it with layout XML instead of the system configuration, for example because you are developing an extension or only need it on certain pages, use the before_body_end container. You can put the JavaScript in a template:

<reference name="before_body_end">
    <block type="core/template" name="any_unique_name_here" template="path/to/your/template.phtml" />
</reference>

Or add it as a text block directly in XML:

<reference name="before_body_end">
    <block type="core/text" name="any_unique_name_here">
        <action method="setText">
            <text><![CDATA[
<script type="text/javascript">
console.log('It works!');
</script>
]]></text>
        </action>
    </block>
</reference>
Related Topic