How to specify absolute external paths (e.g. CDN) using “addJS” in .xml in /layout (sub)directory?

magento.stackexchange https://magento.stackexchange.com//questions/73341

  •  13-12-2019
  •  | 
  •  

Question

It appears ABSOLUTE filespecs to external files work for CSS (addLinkRel) but not JS (addJs). The sytem always prepends the site domain+path when using addJs.

<layout version="1.0.0">
    <adminhtml_mypage_index>
        <reference name="head">
            <action method="addJs">
              <!-- This does not work ... -->
              <name>//cdn.... .js</name>
            </action>
            <action method="addLinkRel">
                <!-- ... but this does! -->
                <rel>stylesheet</rel>
                <href>//cdn.... .css</href>
            </action>

This forces me to a confusing inconsistency whereby the CSS files on, say a CDN, can be specified declaratively in the layout .xml, but the associated external JS files on the same CDN need to go in the .phtml. Is there a better way?

One would hope one could could keep these file references together in a logical place.

Should I move both the JS and CSS declarations from the layout .xml to the associated .phtml so that they're kept together? One could argue this then defeats the purpose of using .xml to declaratively specify JS and CSS.

Suggestions?

Was it helpful?

Solution

To add the external js file there is no native function in magento. But you can add the js file through layout by following code

<reference name="head">
    <block type="core/text" name="unique-name">
        <action method="setText">
            <text><![CDATA[<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>]]></text>
        </action>
    </block>
</reference>

OTHER TIPS

I like Meenakshi's approach. I use this approach for all third-party scripts. A good example is found here in my canonical question about including jQuery from Google CDN:

Google CDN jQuery with Local Fallback in Magento Layout XML

However, there's another way which may or may not prove appealing: Instead of including in the head with layout XML, instead include it via the Admin panel in System > Config > Design and in the HTML Head dropdown:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top