I am beginner in Magento and I want to add javascript file in body section through layout xml file.
In Magento xml, action method="method_name" refers to a method within the referenced block code. Other block objects may not have the "addJs" method defined.
The "method_name" refers to code that corresponds to that blocks core code. For instance, in app\code\core\Mage\Page\Block\Html\head.php:
public function addJs($name, $params = "")
{
$this->addItem('js', $name, $params);
return $this;
}
So to add external js to any other block, you would have to edit the underlying code (move file to app\code\local... if you attempt it) and add several methods for this to work correctly.
As they say, there is more than one way to skin a cat (not that you would want to...). What would be easier to do is to make a .phtml template file with code to create the external links.
For example if I were to make an ext_js.phtml with this:
<?php $_jsExtNames = array('extra1.js' , 'extra2.js'); ?>
<?php foreach($_jsExtNames as $_jsExtName): ?>
<script src="<?php echo $this->getSkinUrl('js/'.$_jsExtName) ?>"></script>
<?php endforeach; ?>
Where the $_jsExtNames array is a list of the external js scripts in your themes skin/js folder.
The matter of adding it to your XML can change depending on where you are adding it. For default areas, something like this would work if I placed my .phtml file in page/html folder:
<default>
<reference name="footer">
<block type="core/template" name="extra_js" template="page/html/ext_js.phtml" />
</reference>
</default>
That works just fine on its own. If you place it within another block, you will need to call it within that block's template file.
To illustrate that example, if I wanted to place my external js within the category view page, I would add it to category.xml like so:
<catalog_category_layered translate="label">
<label>Catalog Category (Anchor)</label>
<reference name="left">
<block type="catalog/layer_view" name="catalog.leftnav" after="currency" template="catalog/layer/view.phtml"/>
</reference>
<reference name="content">
<block type="catalog/category_view" name="category.products" template="catalog/category/view.phtml">
<!-- Added Line Below -->
<block type="core/template" name="extra_js" template="page/html/ext_js.phtml" />
Now we'll have to call the block by its name by adding this line where we would like it to go in the file catalog/category/view.phtml:
<?php echo $this->getChildHtml('extra_js'); ?>
That should work, I was testing it all out on my install while I was typing.