Magento 1.7 – Adding JavaScript to Head in Certain Pages

javascriptmagento-1.7theme

I'm trying to add some javascript scripts to the head of certain pages of my magento store (now I need one script in the product pages and other script in checkout, but I will need it in other different pages in the future: homepage, categories…).

I'm new to Magento and read quite a bit about it, but still not sure how to do this in Magento (I've done it successfully in Drupal for example).

It seems that page.xml (or local.xml) would be the right place to put the scripts for the head, but I don't know in those xml files allow "conditionals" (only show this script in this kind of pages…).

Another option seems to be putting the code in head.phtml of the template. This should work, because it accepts php ifs, but I don't know what code and variables should be used for each case (for showing in product pages, or checkout, or homepage, etc.)

What is the best/cleanest option for this? Could you please give me a code example of how would it be implemented or point to me to the relevant documentation page?

Thanks a lot!

P.S.: I don't think it makes any difference for this matter, but the javascript codes that I'm trying to implement are for using the Google Analytics Content Experiments API (https://developers.google.com/analytics/solutions/experiments-client-side)

Best Answer

Add the following in your local.xml layout file (app/design/frontend/{interface}/{theme}/layout/local.xml) right under the <layout> tag this:
For product pages

<catalog_product_view>
    <reference name="head">
        <block type="core/text" name="some_name" as="some_name">
            <action method="setText">
                <text><![CDATA[YOUR TEXT GOES HERE]]></text>
            </action>
        </block>
    </reference>
</catalog_product_view>

For the checkout page is the same thing, except you need to replace the top tag with <checkout_onepage_index>. So the section above becomes:

<checkout_onepage_index>
    <reference name="head">
        <block type="core/text" name="some_name" as="some_name">
            <action method="setText">
                <text><![CDATA[YOUR TEXT GOES HERE]]></text>
            </action>
        </block>
    </reference>
</checkout_onepage_index>

it works the same for any other page. You just need to know the correct page handle (top tag). For index is cms_index_index, for cart is checkout_cart_index.

Related Topic