【问题标题】:Include scripts/styles only once in OctoberCMS在 OctoberCMS 中仅包含一次脚本/样式
【发布时间】:2021-01-10 11:47:30
【问题描述】:

OctoberCMS 有一个非常方便的功能,允许使用 {% put scripts %} 在页面或部分中注入脚本或样式。我面临的问题是,每次我包含一个包含它的部分时,它都会复制添加的脚本。

是否可以设置一个功能以便只放置一次脚本?

我面临的一个典型用例是一个滑块部分,我只想在显示的页面中实际使用它时加载它的脚本和样式,但是如果我有多个滑块,那么我不想包含多个脚本次。

【问题讨论】:

    标签: octobercms


    【解决方案1】:

    有两种解决方案,您可以使用其中任何一种,非常适合您。

    1.你可以给你的脚本unique id 来检查它是否已经存在并基于它包含它

    我们制作了 2 个脚本

    1. check-script 将检查是否添加了主脚本,如果没有 添加添加它,或者如果已经存在则跳过添加。
    2. 你的主脚本

    check-script.js

    window.scriptIncluded = document.getElementById('script-included');
    
    // check if script is already loaded if not include it
    if(!window.scriptIncluded) {
    
        scriptTag = document.createElement('script');
        scriptTag.id = 'script-included'; // <- USE YOUR ID HERE ITS JUST FOR DEMO
        scriptTag.src = '/plugins/.../assets/bundle.js';
    
        // add script first time
        document.head.append(scriptTag);
    }
    

    现在在您的 {% put scripts %} 中包含此脚本

    {% put scripts %}
        <script type="text/javascript" src="/plugin/.../js/check-script.js"></script>
    {% endput %}
    

    是的check-script.js 可能包含多次,但它只会加载您的主脚本一次。

    2。更好的解决方案是从组件文件中添加脚本并在那里检查

    public function onRun()
    {    
        // if global variable is not set only then include script
        if(!isset($GLOBALS['script-included'])) { // <- USE YOUR ID HERE ITS JUST FOR DEMO
    
            $this->addJs('/plugins/.../assets/main-script.js');
    
            // set global variable so next time script will not be included
            $GLOBALS['script-included'] = true;
        }
    }
    

    如有任何疑问,请发表评论。

    【讨论】:

      猜你喜欢
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多