Magento - 动态加载CSS和JS

Magento - Load dynamically CSS and JS

本文关键字:JS CSS 加载 动态 Magento      更新时间:2023-09-26

我们希望为magento系统中的页面动态加载css和javascript文件。由于js和css文件的增长,我们希望将它们拆分为单独的文件并为当前页面加载它们。我们使用CMS高级内容管理器来管理我们的页面内容。因为我们在CMS中有类似内容类型的东西,所以我们想弄清楚当前页面具有哪种内容类型。引用我们认为通过类型名称加载 css 和 js 文件的类型(因为类型名是别名并且在系统中是唯一的(。因为我没有深入 magento 编码,我不知道我应该从哪里开始。

但也许还有另一种解决方案或已知的解决方案可以实现我们想要的。

您是否尝试过使用XML在特定内容页面上加载JS或CSS?

下面是加载CSS和JS文件的示例。

内容页 => 设计选项卡 => 自定义布局更新 XML。

<reference name="head">
    <action method="addItem"><type>skin_css</type><name>css/your_css.css</name></action>
    <action method="addItem"><type>skin_js</type><name>js/your_js.js</name></action>
</reference>

您可以创建一个扩展来观察"布局加载之前"事件。使用一些请求参数,您可以确定要包含一些 css 或 js 的页面。

例如:

app/code/local/Foo/Bar/etc/config.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Foo_Bar>
            <version>0.1.0</version>
        </Foo_Bar>
    </modules>
    <global>
        <models>
          <foo_bar>
            <class>Foo_Bar_Model</class>
          </foo_bar>
        </models>
    </global>
    <frontend>
        <events>
            <controller_action_layout_load_before>
                <observers>
                    <customer_is_logged_in_observer>
                        <class>foo_bar/observer</class>
                        <method>beforeLoadLayout</method>
                    </customer_is_logged_in_observer>
                </observers>
            </controller_action_layout_load_before>
        </events>
     </frontend>
</config>

app/code/local/Foo/Bar/Model/Observer.php

class Foo_Bar_Model_Observer
{
    public function beforeLoadLayout($observer)
    {   
        if(Mage::app()->getRequest()->getControllerName()=='page' && 
            Mage::app()->getRequest()->getRouteName()='cms')
        {
            $head=$observer->getEvent()->getLayout()->getBlock('head');
            $head->addItem('skin_js', 'js/foo.js');
            $head->addItem('skin_css', 'css/foo.css');
        }
    }
}

只需查看模块文档,即可实现动态布局。因此,您可以为特定内容类型添加特定布局:

ACM for Magento 1.x: (页末( https://www.advancedcontentmanager.com/documentation/content/php-helper-methods-render-methods

ACM for Magento 2.x: https://www.advancedcontentmanager.com/documentation/m2/developers/dynamic-layout-handle