所以我终于找到了一个黑客来做到这一点。我扩展了一个新ClientScript
类并修改了registerScript
方法,以便它接受另一个参数$level
。
public function registerScript($id, $script, $position = self::POS_END, $level = 1);
就像在 CSS 中$level
一样z-index
,除了 is 的数量越大,$level
脚本的位置就越低。
例如
Yii::app()->clientScript->registerScript('script1', '/** SCRIPT #1 **/', CClientScript::POS_END, 1);
Yii::app()->clientScript->registerScript('script2', '/** SCRIPT #2 **/', CClientScript::POS_END, 2);
Yii::app()->clientScript->registerScript('script3', '/** SCRIPT #3 **/', CClientScript::POS_END, 1);
即使script3
在 之后声明script2
,在渲染的脚本中,它也会显示在上面,script2
因为 的$level
值script2
大于script3
's。
这是我的解决方案的代码。它就像我想要的那样工作,虽然我不确定排列方法是否足够优化。
/**
* ClientScript manages Javascript and CSS.
*/
class ClientScript extends CClientScript {
public $scriptLevels = array();
/**
* Registers a piece of javascript code.
* @param string $id ID that uniquely identifies this piece of JavaScript code
* @param string $script the javascript code
* @param integer $position the position of the JavaScript code.
* @param integer $level the rendering priority of the JavaScript code in a position.
* @return CClientScript the CClientScript object itself (to support method chaining, available since version 1.1.5).
*/
public function registerScript($id, $script, $position = self::POS_END, $level = 1) {
$this->scriptLevels[$id] = $level;
return parent::registerScript($id, $script, $position);
}
/**
* Renders the registered scripts.
* Overriding from CClientScript.
* @param string $output the existing output that needs to be inserted with script tags
*/
public function render(&$output) {
if (!$this->hasScripts)
return;
$this->renderCoreScripts();
if (!empty($this->scriptMap))
$this->remapScripts();
$this->unifyScripts();
//===================================
//Arranging the priority
$this->rearrangeLevels();
//===================================
$this->renderHead($output);
if ($this->enableJavaScript) {
$this->renderBodyBegin($output);
$this->renderBodyEnd($output);
}
}
/**
* Rearrange the script levels.
*/
public function rearrangeLevels() {
$scriptLevels = $this->scriptLevels;
foreach ($this->scripts as $position => &$scripts) {
$newscripts = array();
$tempscript = array();
foreach ($scripts as $id => $script) {
$level = isset($scriptLevels[$id]) ? $scriptLevels[$id] : 1;
$tempscript[$level][$id] = $script;
}
foreach ($tempscript as $s) {
foreach ($s as $id => $script) {
$newscripts[$id] = $script;
}
}
$scripts = $newscripts;
}
}
}
所以我只需要将类作为clientScript组件放在配置中
'components' => array(
'clientScript' => array(
'class' => 'ClientScript'
)
)