B-219 Sec-55 Noida, India
+918010221733

How to Properly Add an External JS/CSS file to 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):

 <reference name=”head”>
 <block type=”core/text” name=”jquery”>
 <action method=”setText”>
 <text><![CDATA[<script src=”//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js”></script>]]></text>
 </action>
 </block>
 </reference>
 <reference name=”head”>
  <block type=”core/text” name=”jquery”>
   <action method=”setText”><text><![CDATA[<script src=”//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js”></script>]]></text></action>
   </block>
   </reference>
  
   For including an external CSS file:
  
   <reference name=”head”>
   <block type=”core/text” name=”mybuyscsscode”>
   <action method=”setText”><text><![CDATA[<link href=”//t.p.mybuys.com/css/mbstyles.css” rel=”stylesheet” type=”text/css” id=”mybuysstyles”>]]></text></action>
    </block>
    </reference>
   
     <reference name=”head”> <block type=”core/text” name=”mybuyscsscode”>
      <action method=”setText”><text><![CDATA[<link href=”//t.p.mybuys.com/css/mbstyles.css” rel=”stylesheet” type=”text/css” id=”mybuysstyles”>]]></text></action>
      </block>
     </reference>

(Visited 66 times, 1 visits today)

Leave a reply

You must be logged in to post a comment.