How to move the JS file includes to footer in Magento

In order to reduce the initial load time of page, it is recommended to move all the JS includes in the <head> section of web page to the footer. Lets see how we can do it in Magento.

Step 1: Add Layout Updates

Create a child block of “before_body_end” named “foot” similar to the head block in local.xml file as shown below:


<?xml version="1.0" ?>
<layout version="0.1.0">
<default>
<reference name="before_body_end">
<block type="page/html_head" name="foot" as="foot" after="-" template="page/html/foot.phtml"/>
</reference>
</default>
</layout>

 

Now add the JS includes to this block.

 

If you want to include the JS files in all pages then you need to update the <default> handle as shown below:


<?xml version="1.0" ?>
<layout version="0.1.0">
<default>
<reference name="before_body_end">
<block type="page/html_head" name="foot" as="foot" after="-" template="page/html/foot.phtml">
<action method="addItem"><type>js</type><name>custom_lib/custom.js</name></action>
<action method="addItem"><type>js</type><name>custom_lib/custom_ie.js</name><params/><if>lt IE 7</if></action>
<action method="addItem"><type>skin_js</type><name>js/custom.js</name></action>
<action method="addItem"><type>skin_js</type><name>js/custom_ie6.js</name><params/><if>lt IE 7</if></action>
</block>
</reference>
</default>
</layout>

 

In order to include the JS files on specific pages say non-anchor category page, we will update the page specific layout handles as shown below:


<catalog_category_default>
<reference name="foot">
<action method="addItem">
<type>skin_js</type>
<name>js/custom_catalog.js</name>
</action>
</reference>
</catalog_category_default>

 

Step 2: Create .phtml view file

Create the .phtml file page/html/foot.phtml and add the following contents:


<?php echo $this->getCssJsHtml() ?>

 

Step 3: Update the page template layout  file(s)

Open up your page template files “1column.phtml”, “2columns-left.phtml” etc. and verify that you have the below line added near the closing of </body> tag:


<?php echo $this->getChildHtml('before_body_end') ?>

If missing add it.

 

NOTE:

Before you move all Magento JS file included in the head section, make sure that you have updated your code so that no JS function is called before all JS files get loaded.

For example:

Magento quick search form [catalogsearch/form.mini.phtml] has the following inline script:


<script type="text/javascript">
//<![CDATA[
var searchForm = new Varien.searchForm('search_mini_form', 'search', '<?php echo $this->__('Search Redset...') ?>');
//]]>
</script>

It gets called as soon as it gets loaded, so such code should be put in document ready handler.

Thus, the rule to follow is: Add a document ready handler to the inline JS function calls or move all inline JS to an external file and load in the footer after loading the dependent library files.

Leave a Comment

Back to top