How to add External JS Or CSS Assets Using Magento Layout XML

12 May 2015| Post by Graham

AuthorGraham

[intro]

Whether you want to load in a Google Font, jQuery or any other Javascript library using a CDN (Content Delivery Network), unfotunately Magento doesn’t allow you do this using the layout XML – however with just a few simple steps, we can create a module that allows you to add external assets using the Magento Layout XML.

[/intro]

Step 1. Create the Module

{{app-dir}}/app/etc/modules/My_ExternalAssets.xml

[cc lang=”xml”]



true
local



[/cc]

Step 1. Include the Module

This file lets Magento know to include the “ExternalAssets” module during the module initialisation.

{{app-dir}}/app/code/local/My/ExternalAssets/Block/Page/Html/Head.php

[cc lang=”php”] ‘, $href, $params
);
break;
case ‘link_rel’:
$lines[$itemIf][‘other’][] = sprintf(‘‘, $params, $href);
break;

case ‘external_js’:
$lines[$itemIf][‘other’][] = sprintf(‘‘, $href, $params);
break;

case ‘external_css’:
$lines[$itemIf][‘other’][] = sprintf(‘‘, $href, $params);
break;
}
}

}
[/cc]

Step 3. Overwrite the class

This class overwrites Magento’s default “Mage_Page_Block_Html_Head” class adding the two methods “addExternalItem” and “removeExternalItem”. It also overwrites the protected function “_seperateOtherHtmlHeadElements” with instructions on what format to output the new “external_js” and “external_css” asset types.

Also note that the default type for the asset is “external_js”, I have done this as I anticipate this will be the most commonly used functionality.

{{app-dir}}/app/code/local/My/ExternalAssets/etc/config.xml

[cc lang=”xml”]



0.0.1




My_ExternalAssets_Block_Page_Html_Head



[/cc]

This config file instructs Magento to look for the “My_ExternalAssets_Block_Page_Html_Head” class is whenever the “page/html_head” block is loaded. This allows us to overwrite a Magento core file without editing it directly.

Usage

Here is an example usage of the layout XML required to output external assets :

{{app-dir}}/app/design/frontend/{{theme-folder}}/default/layout/page.xml

[cc lang=”xml”]




http://example.com/example.js



http://example.com/example.js
external_css

[/cc]

Once you have refreshed your Magento cache, you will be able to add external assets using Magento’s layout XML configuration.

Scroll