Magento 1 - add inline javascript to product page via layout update xml code

javascript, layout, magento, xml

Solution

It's cleaner to load the javascript from file. You do not necessarily need all that blocks but can do it like:

<default translate="label" module="page">   
    <reference name="head">
        <action method="addJs"><script>path/to/script.js</script></action>
    </reference>
</default>

Path is relative path from `js` folder in magento root.

To add javascript to xml directly (which I do not recommend) you can use CDATA, like:

<reference name="head">
    <block type="core/text" name="your.block.name">
        <action method="setText">
            <text><![CDATA[<script type="text/javascript">alert('hello');</script>]]></text>
        </action>
    </block>
</reference>

Problem

Hi i want to use google analytics's AB-Testing engine. Therefore i have to add a javascript-snippet to single product pages. My intend was to add it in the description or short-description. It is working, but it is insufficient, because the script makes a redirect, which means the page loads half and then is redirected. Google says i should add the script in the head-tag. Is it possible to insert the script as "custom layout update" here: i could imagine something like ``` <default translate="label" module="page"> <label>All Pages</label> <block type="page/html" name="root" output="toHtml" template="page/3columns.phtml"> <block type="page/html_head" name="head" as="head"> <action method="addJs"><script>alert('hello')</script></action> </block> </block> </default> ```

Original source