How to Add External JS to CMS Page

javascript

I'm trying to add an external javascript file to a CMS page using the Layout Update XML feature, and have had no luck. I have tried the following

<action method="setText"><text><![CDATA[<script src="//ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>]]></text></action>

<action method="addJs"><script>http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0</script></action>

<action method="addItem">
<type>skin_js</type>
<name>http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0</name>
<params/>
</action>

The first two don't work at all, the third one adds it but prepends the skin url to the src.

Best Answer

It looks as if you haven't formatted the XML properly and it needs to be enclosed in a layout handle.

Here are the problems one by one:

setText is a method for a Core Text block type

You need to put this inside of a core/text block for it to do anything at all:

<block type="core/text" name="mapcontrol.script.block">
            <action method="setText"><text><![CDATA[<script src="//ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>]]></text></action>
</block>

Layout instructions require a layout handle

You need to wrap these in a handle and a block reference where they'll be inserted:

<?xml version="1.0"?>
<layout>
    <default>
        <reference name="before_body_end">
            <block type="core/text" name="mapcontrol.script.block">
                <action method="setText"><text><![CDATA[<script src="//ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>]]></text></action>
            </block>
        </reference>
    </default>
</layout>

addJs is a method exclusive to Mage_Page_Block_Html_Head

You can only call it on a block of that type, e.g.:

<block type="page/html_head">
<action method="addJs"><file>mapcontrol/mapcontrol.js</file></action>
</block>

But really this is meant for local files only. This is because it attempts to prepend the type as it's really just a wrapper for addItem, which you then try to call again later.

addJs calls addItem but addJs differs from the skin_js type

They're located in different places on the filesystem.

  • addJs attempts to include from [document_root]/js/your/file/here.js
  • addItem with type skin_js attempts to include from [document_root]/skin/frontend/[package]/[theme]/js/your/file/here.js

Conclusion

To wrap up - you've made a few errors here. This should work for you and uses the setText method of a core/text block type:

<?xml version="1.0"?>
<layout>
    <default>
        <reference name="before_body_end">
            <block type="core/text" name="mapcontrol.script.block">
                <action method="setText"><text><![CDATA[<script src="//ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>]]></text></action>
            </block>
        </reference>
    </default>
</layout>