In magento I know how to include js files in the page layout file. How though, do i include specific javascript files only on certain pages with my custom module. For example i am writing a custom module that will work with the product view and list pages. I therfore want to have some sort of layout update that i can use with my module that will include my javascript file only on the product view and list pages.
What you need to do is find the layout handles for the pages that you want to include the JS, and add them to your custom module's layout XML. For instance, to include the JS on the product view, you would add the following node to your layout:
<catalog_product_view>
<reference name="head">
<action method="addJs"><script>path/file.js</script></action> **OR**
<action method="addItem"><type>skin_js</type><name>path/file.js</name></action>
</reference>
Choose either option depending on where your JS files live. Have a look in the default catalog.xml or review.xml for examples.
To work out the layout handle (e.g. catalog_product_view), you can use Alan Storm's excellent (and free) LayoutViewer module from his blog.
HTH, JD
Hi Jon, you will need to add a layout update section to your modules config file. based on what you have said you will need something like this in your layout file:
<?xml version="1.0"?>
<layout version="0.1.0">
<catalog_product_view>
<reference name="head">
<action method="addJs"><script>yourscript.js</script></action>
</reference>
</catalog_product_view>
<catalog_category_view>
<reference name="head">
<action method="addJs"><script>yourscript.js</script></action>
</reference>
</catalog_category_view>
</layout>
Then in your modules config file, you will need something like:
<frontend>
<layout>
<updates>
<yourmodule>
<file>yourlayout.xml</file>
</yourmodule>
</updates>
</layout>
</frontend>
This assumes that yourscript.js is sitting in the root of the js folder. Obviously, you dont want to put it here so do what Jonathan advised and use:
<action method="addItem"><type>skin_js</type><name>path/file.js</name></action>
and put your js in your themes skin folder.
Good luck!
Along those lines, does anyone know how to move the js script call to be at the end of the body? best practices say that any unnecessary js should be loaded at the end of the page, not in the head.
I understand that there's some Varien js code that needs to remain in the head, but for anything else...