How to Properly Add an External JS/CSS file to Magento

external-js-css-magento

Sometimes as frontend developers we need to add an external JavaScript or a CSS file. It may be that you need to include the Google Hosted JS libraries or you want to integrate with a third party Marketing or Analytics service. This method that I have used successfully on many sites actually avoids hacking the head.phtml file and keeps the link working properly on both non-secure and SSL driven pages. It also does not require any additional extensions or any files.

Add the following lines in your page.xml layout file inside the <block name=”root” …> which is located inside the main <default> xml node. You probably want to include these lines below the <block name=”head” …> just to make sure the block we are going to change is already defined. Notice: you can also include these lines in your own layout file and make sure your extension includes the layout file in the frontend. Ok, here are the lines:

For including an external JavaScript file (an example of jQuery from Google Hosted Libraries is shown):

For including an external CSS file:

A couple of notes:

  1. Make sure to use <block type=”core/text” …>
  2. Make sure to add the <![CDATA[…]]> special brackets around the actual link
  3. Make sure to omit the ‘http’ portion and start your link with ‘//’ in order for the links to work properly with the SSL driven pages.

Enjoy!

One Comment

  • John P. says:

    Ahh.. that is what I was missing. Removing the ‘http’ from the links helped me solve the issue I had with SSL secure pages. Thanks.