Search code examples
phpjquerymagentofancybox

Adding External Scripts to one Magento page


I have read up on this a bit, but still must be missing something.

I have a photo gallery page, and am using fancy box to show larger versions of the images on click. There are two scripts I need to add for fancybox, a jquery and fancybox script.

I have gone into the gallery xml page, and added this code into it so that it looks like this:

    <reference name="head">
        <action method="addJs">
            <type>jquery_js</type>
            <script>http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js</script>
        </action>
        <action method="addJs">
            <type>fancybox_js</type>
            <script>/fancybox/jquery.fancybox-1.3.4.pack.js</script>
        </action>

    </reference>

    <reference name="root">
        <action method="setTemplate">
            <template>page/1column.phtml</template>

...

but then I don't know how to use them in my view. When I go to the page, I am still getting 404 errors for these scripts. I am probably missing some simple things as I've never tackled a magento issue before.

Thanks in advance, Alyssa


Solution

  • To call an external file in Magento layout XML you can add a block

    <reference name="head">
        <block type="core/text" name="jquery.cdn.whatever.you.want.to.call.it">
            <action method="setText">
                <text><![CDATA[<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>]]></text>
            </action>
        </block>
    </reference>
    

    For your local fancybox file, (I presume it's locally hosted?), it depends where you saved it, there's a root js folder, so if it's in there you can use:

    <action method="addJs">
        <script>fancybox/jquery.fancybox-1.3.4.pack.js</script>
    </action>
    

    You don't need to a add <type> as addJs already defines it as a JS type and fancybox_js isn't an option as far as I'm aware for the attribute, also note there's no / at the start, the script tag will add the path itself with a trailing slash.

    If it's inside your theme folder you can use:

    <action method="addJs">
        <type>skin_js</type>
        <script>fancybox/jquery.fancybox-1.3.4.pack.js</script>
    </action>
    

    This will look in your theme js folder for a referred file.