How to include Js File in Magento?

JavaScript is important for making your storefront dynamic and interactive.you need for adding external files into your Magento layout
If you had then you know that you cannot do that from your XML layout files using methods/action.

Try adding the following to your layout.xml file within <reference name="head">

<layout> 
<default>
<reference name="head">
<action method="addJs">
<script>custom-script.js</script>
</action>
</reference>
</default>
</layout>

And put the custom-script.js file in the js folder on root.

You can add your custom JS file in your theme's local.xmllocated in:

app/design/frontend/{design package}/{theme}/layout/local.xml

<?xml version="1.0"?>
 <layout version="0.1.0">
    <default>
       <reference name="head">
          <action method="addItem"><type>skin_js</type><name>js/script_name.js</name></action>
       </reference>
    </default>
 </layout>

Add js file into Block

protected function _prepareLayout()
    {
        $this->getLayout()->getBlock('head')->addJs('path/from/js/folder/to/your/file.js');

        return parent::_prepareLayout();
    }

 

Add js file into Controller

If you want to include javascript for any particular controller then put this code in your module's layout.xml like below

<layout>  
<yourpackage_yourmodule_yourcontroller_action translate="label" module="yourpackage_yourmodule">       
    <reference name="head">
        <action method="addJs">
            <script>custom-script.js</script>
        </action>
    </reference>
</yourpackage_yourmodule_yourcontroller_action>
</layout>

And put custom-script.js file under yourMagentoDirectory/js folder.

To add an external JS without any problem use this:

<reference name="head">
   <block type="core/text" name="google.cdn.jquery">
      <action method="setText">
        <text>
           <![CDATA[<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><script type="text/javascript">jQuery.noConflict();</script>]]>
        </text>
      </action>
   </block>
</reference>

 

 

Join our Newsletter

Never miss the latest offers, voucher codes and useful articles delivered weekly in your inbox.