For this mission we have some approaches too. The easiest way is to just place your js code into one of yours .phtml templates, but more likely you’ll want to place it into html head of your page code, especially if the same script will be used on different pages.
Adding .js files from XML layout
Ok this way is pretty straight forward. There is two actions in layout markup to do it. Lets look at this code
You see three actions here. Well actually first two do exactly same thing as
addJs method just calls
addItem method with js type argument as you can see in Mage_Page_Block_Html_Head core class:
public function addJs($name, $params = "")
$this->addItem('js', $name, $params);
In second case path is relative to your themes skin folder. If you work in base default theme Magento will search for include of your file here /skin/frontend/base/default/js/my/script.js.
For some reason you may need to do the same from your Magento script code instead of layout XML file. This is possible as well. All you need for it is to get instance of your head block and call addJs or addItem methods on it. For example in your controller code you can do:
$head = $this->getLayout()->getBlock('head');
var uploadPath = '<?php echo Mage::getUrl('images/upload'); ?>';
awesomePlugin.initSettings(<?php echo $jsonObject; ?>);
<?php if ($needIt) : ?>
<?php endif ; ?>
<block type="core/template" name="my_script" template="theme/script.phtml" />
This will include you script located in your theme script.phtml template file. If you need it to be on all frontend pages just place it inside of default handle.
What about Adminhtml
$this->getChildHtml() that front end one does. So your blocks will not be rendered in backend head. Guess Magento developers had some reasons to do it.
<?php echo $this->getChildHtml(); ?>
This will make backend head file render added blocks just like the front end one does. So you can add any number of your js script codes from your block templates like we described before.
By the way same technologies described in this article was used in development of our Slider Revolution Magento Extension.