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

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


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>


my solution was to extend the head block:

<?phpclass Company_Modulename_Block_Html_Head extends Mage_Page_Block_Html_Head {    public function addInlineJs($name)    {        $this->addItem('inlinejs', $name);        return $this;    }    public function getCssJsHtml()    {        $html = parent::getCssJsHtml();        foreach ($this->_data['items'] as $item) {            if($item['type']=='inlinejs') {                $html .= sprintf('<script type="text/javascript">%s</script>' . "\n", $item['name']);            }        }        return $html;    }}

now i can use it like that

<reference name="head">       <action method="addInlineJs"><script>alert('cool');</script></action></reference>