How to add a JS or CSS file only on Home page in Magento

In order to optimize the performance of Magento websites it is recommended that you include only the relevant JS Or CSS files on a page. Generally all Magento websites have a slider on home page, so it is good idea to include the slider JS and CSS files only on the home page if none of the other web pages implement a slider.

Lets see how to do it.

If you open up the base Magento layout file cms.xml and look at the “cms_index_index”tag, you will see the below content:


<cms_index_index translate="label">
<label>CMS Home Page</label>
</cms_index_index>

Now to add our JS and CSS to home page only we need to them in this section. So, you can copy the base Magent cms.xml file into your custom theme and update or you can create a local.xml file in your custom theme and add “cms_index_index” section as shown below:

1. Adding JS and CSS files from the skin directoy.


<cms_index_index translate="label">
<label>CMS Home Page</label>
<reference name="head">
<action method="addCss">
<stylesheet>css/custom.min.css</stylesheet>
</action>
<action method="addItem">
<type>skin_js</type>
<name>js/custom.min.js</name>
</action>
</reference>
</cms_index_index>

 

2. Style CSS can also be included as shown below


<reference name="head">
<action method="addItem">
<type>skin_css</type>
<name>css/custom.min.css</name>
</action>
<reference name="head">

3. In order to add JS files from the js directory the following xml can be considered


<reference name="head">
<action method="addJs">
<script>custom/custom.min.js</script>
</action>
<reference name="head">

 

Managing from the Magento Admin

 

Home Page Design Tab

 

If you do not want to change the layout xml file then you can do the same from Magento admin. Open the Home page in Magento admin, click the “Design tab”. In the “Layout Update XML” area, paste xml similar to the below and “Save” the page.


<reference name="head">
<action method="addCss">
<stylesheet>css/custom.min.css</stylesheet>
</action>
<action method="addItem">
<type>skin_js</type>
<name>js/custom.min.js</name>
</action>
</reference>

“cms_index_index” tag is not require here.

NOTE: Just like this you can add a JS or CSS file to any CMS page from Magento Admin.

 

 

Leave a Comment

Back to top