How to add JS programmatically in Magento?

I need to add a JS file conditionally and programmatically inside a block file. I tried with these codes:

if (Mage::getStoreConfig('mymodule/settings/enable')) {
$this->getLayout()->getBlock('head')->addJs('path-to-file/file1.js');
} else {
$this->getLayout()->getBlock('head')->addJs('path-to-file/file2.js');
}

However, regardless of the setting, none of these files are downloaded. I even tried to eliminate the condition and explicitly upload only one file, but it still doesn't work. What have I done wrong here?

+5
source share
3 answers

The problem here is probably one of the processing procedures. I assume your PHP code is evaluated after rendering the head block. Although your code successfully updates an instance of the head block class, this happens after the result has been generated from that instance.

addJs() XML, . , ifnotconfig, .

, script , .

<?php 
class My_Module_Helper_Class extends Mage_Core_Helper_Abstract
{
    public function getJsBasedOnConfig()
    {
        if (Mage::getStoreConfigFlag('mymodule/settings/enable')) {
            return 'path-to-file/file1.js';
        }
        else {
            return 'path-to-file/file2.js';
        }
    }
}

XML:

<?xml version="1.0"?>
<layout>
    <default>
        <reference name="head">
            <action method="addJs">
                <file helper="classgroup/class/getJsBasedOnConfig" />
                <!-- i.e. Mage::helper('module/helper')->getJsBasedOnConfig() -->
            </action>
        </reference>
    </default>
</layout>
+18
$this->getLayout()->getBlock('head')->addJs('path');

, .

+3

, , - , local.xml:

<layout>
    <default>
        <reference  name="head">
            <action ifconfig="path/to/config" method="addJs">
                <script>pathto/file.js</script>
            </action>
        </reference>
    </default> 
</layout>

, JS, /js/. , skin_js skin_css.

PS. CE 1.9

+1

All Articles