Adding javascript in Magento head block

Adding javascript in Magento head block

Sometimes when working with Magento you’ll want to add some Javascript code. It could be third party library or your own custom code. Lets see the ways of adding javascript in Magento.

In most cases your Javascript code you want to include to your Magento theme or extension are located or can be placed in separate .js files. To include them we can use built in Magento tools for adding them. The really great advantage of it is speed up of your store as its engine merges all .js files together. This allows to decrease number of http request to your server on page load so the page loads faster. And if you want to bring even more power up to it — there is some third party extensions that can minify your Javascript code.

There will be more details below on including js files, but sometimes you need to have some inline custom javascript added to yours code. Like when it needs to be generated by server side script or to include some data for your frontend. For example url paths generated by Magento or JSON encoded settings or objects for your javascript code.

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.

You can achieve it by adding your custom blocks to head layout block or by overriding head.phtml template. There is some specific issue if you working on Magento backend and need to inject your javascript code to Adminhtml head.

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

<thats_my_handle>
	<reference name="head">
		<action method="addJs"><script>my/script.js</script></action>
		<action method="addItem">
			<type>js</type>
			<name>my/script.js</name>
		</action>
		<action method="addItem">
			<type>skin_js</type>
			<name>my/script.js</name>
		</action>
	</reference>
</thats_my_handle>

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);
    	return $this;
}

So what is difference between “addItem js” in first two actions and “addItem skin_js” in third action? Its about the path where your javascript files be located. In js case path to file you specify in argument is relative to root js Magento folder, in our example it will be /js/my/script.js. As you see it is good idea to place it some your own folder to not create mess with other .js files there.

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.

How to decide where to put your script file? If it is some library or javascript code to be shared between different extensions root /js folder is good solution. And if you work on some theme related stuff you’ll prefer to stick to skin theme folder.

Adding Javascript files programmatically from code

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');
$head->addJs('my/script.js');
$head->addItem('js', 'my/script.js');
$head->addItem('skin_js', 'my/script.js');

Like in our first example first two methods do the same and inject js from root /js folder and the last line include your javascript code from skin theme path.

How to add custom Javascript code to Magento

In some cases you can’t just include static .js files as you need some dynamic data included into it. Like when you want some part of code depend of some conditions logic in your script or init javascript variables with data from generated by Magento. Something like this:

var uploadPath = '<?php echo Mage::getUrl('images/upload'); ?>';
awesomePlugin.initSettings(<?php echo $jsonObject; ?>);
<?php if ($needIt) : ?>
awesomePlugin.doIt();
<?php endif ; ?>

Of course you can place this code right in your .phtml template. But sometimes you need to include it in head of your page. Especially if it does init of data that be used by other scripts in different pages of your store. To do this you can add your own block with template that have your javascript code to page head. You can do it in your themes layout XML file:

<thats_my_handle>
<reference name="head">
<block type="core/template" name="my_script" template="theme/script.phtml" />
</reference>
</thats_my_handle>

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

Well the way of adding javascript files to Magento page head works the same in both front end and in Adminhtml backend. But if you deal with adding custom javascript code and try the way of adding block to backend head like was explained in previous section — you’ll have no luck with it. As adminhtml head template don’t calls $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.

Anyway there is workarounds for it too. We can copy backend head.phtml template which is located at /app/design/adminhtml/default/default/template/page/head.phtml to your theme folder. Then you can just edit this file in new location and put your custom javascript code there. Or even better approach is to add this line of code to 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.

One thought on “Adding javascript in Magento head block

Leave a Reply

Your email address will not be published. Required fields are marked *