OK, I decided to write this post because it pulls together some useful information from disparate sources (Google, the Magento Boards and Stackoverflow) which when put together should be a useful resource. So the topic – how you make sure that Magento only includes certain scripts on specific CMS pages, or all CMS Pages, or removes them from the checkout pages etc etc.
First of all – why would you want to do this? Well the immediate answer is for efficiency reasons. If only your contact page uses the Google Maps API script then why would you load it in every other page, the user might not even view the contact page. Similarly for more chunky scripts – if the Isotope jQuery script (or even jQuery herself) is only loaded on the Gallery page then you don’t want to force the user to download it on the homepage. This is especially true for responsive designs, you get mobile device users pulling down all sorts of JS and CSS files over a 3G network when they might not even be used.
So how to do you then add and remove the Javacsript depending on which page you are on. You do it via your local.xml file which you create in your active theme’s layout directory.
<?xml version="1.0"?> <layout version="0.1.0"> <default> // default stuff in here, ie removing the Compare function from the right sidebar altogether <reference name="right"> <remove name="catalog.compare.sidebar"/> </reference> <default> </layout>
You can add script to the Product view page on like this;
<catalog_product_view> <reference name="head"> <!--PrettyPhoto--> <action method="addCss" ><stylesheet>css/prettyPhoto.css</stylesheet></action> <action method="addItem"><type>skin_js</type><name>js/jquery.prettyPhoto.js</name><params/></action> <action method="addItem"><type>skin_js</type><name>js/load.prettyPhoto.js</name><params/></action> </reference> </catalog_product_view>
Or you could target all CMS pages;
<cms_page> <reference name="head"> <action method="addItem"> <type>skin_js</type> <name>js/script.js</name> </action> </reference> </cms_page>
Or, as in the case for the Sagepay checkout you would strip everything out in the checkout;
<checkout_onepage_index translate="label"> <reference name="head"> <action method="removeItem"> <type>skin_js</type> <name>js/jquery-1.7.2.min.js</name> </action> <action method="removeItem"> <type>skin_js</type> <name>js/jquery.easing.js</name> </action> // // etc etc // </reference> </checkout_onepage_index>
OK, last one then. How do you add scripts on one specific CMS page. Well the answer to that is that you don’t do it via local.xml – you do it in the backend. You would go to CMS->Pages and click to edit, then go to the Design tab (yes, that one you’ve always looked at and thought ‘I’ll get around to working out what that does at some point’). And you add you layout upate in there;
<reference name="head"> <action method="addItem"> <type>skin_js</type> <name>js/locationmap.js</name> </action> </reference>