【问题标题】:How to restrict to load same js multiple times如何限制多次加载相同的js
【发布时间】:2014-05-02 12:20:47
【问题描述】:

我说的是 CakePHP Helper。我想使用 CakePHP 的助手加载 JS 文件。

考虑Helper类的构建会加载所有必要的JS文件。

但是,我需要在一个视图中多次调用该 Helper。因此,JS文件可能会被多次调用。我只想加载这些 JS 文件一次。

谁能帮我介绍一下这个?

这将是我的助手脚本

<?php
App::uses('AppHelper', 'View/Helper');

/**
 * @alias Mathjax Class for helper
 * @description This class is to define helper in cakephp.
 */
class MathjaxHelper extends AppHelper {

    /*
     * Constructor of the class.
     */
    function __construct(View $View, $settings = array()) {
        parent::__construct($View, $settings);
        //login to load all necessary JS files.
    }

    function create() {
        //this function will return the helper html
    }

}

【问题讨论】:

    标签: javascript php cakephp cakephp-2.0


    【解决方案1】:

    使用 HtmlHelper::script

    如果您使用HtmlHelper::script 方法和'inline' =&gt; false 加载js 文件,它们将默认被包含一次

    布局文件

    要使用此方法,请确保在布局文件中回显了 $scripts_for_layout 变量。例如:

    <html>
        <head>
            ...
        </head>
        <body>
            ...
    
            <?php echo $scripts_for_layout ?>
        </body> 
    </html>
    

    查看文件

    在您的视图、元素或助手中 - 只需确保使用内联参数调用脚本方法:

    <?php $this->Html->script('my', array('inline' => false)); ?>
    

    通过这种方式,使用给定 js 文件调用脚本方法的频率无关紧要 - 它只会在结果 html 输出中出现一次。

    【讨论】:

    • 您也可以根据文档使用$options['once']
    • 是的,但这仅在将 js 脚本内联转储到视图文件中时才相关(不应该这样,我也不鼓励这样做)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2012-09-13
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多