我说的是 CakePHP 助手。我想使用 CakePHP 的帮助程序加载 JS 文件。
考虑一下 Helper 类的构造将加载所有必需的 JS 文件。
但是,我需要在单个 View 中多次调用该 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
}
}
最佳答案
使用 HtmlHelper::script
如果您使用HtmlHelper::script方法,使用 'inline' => false
来加载 js 文件,默认情况下它们将被包含一次。
布局文件
要使用此方法,请确保在布局文件中回显 $scripts_for_layout
变量。例如:
<html>
<head>
...
</head>
<body>
...
<?php echo $scripts_for_layout ?>
</body>
</html>
查看文件
在您的 View 、元素或助手中 - 只需确保使用内联参数调用脚本方法即可:
<?php $this->Html->script('my', array('inline' => false)); ?>
通过这种方式,使用给定的 js 文件调用脚本方法的频率并不重要 - 它只会在生成的 html 输出中出现一次。
关于javascript - 如何限制多次加载同一个js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23428064/