在布局的头部放置条件脚本


Placement of conditional script in head section of a layout

在我的布局中,我使用了一堆JavaScripts。其中两个脚本是有条件的,它们应该只为IE9加载。剩下的一个应该为所有浏览器加载。

为了实现这一点,我在我的引导课程中做了以下工作。

$this->_view->headScript ()->appendFile ( '//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js', 'text/javascript', array('conditional' => 'lt IE 9'));
$this->_view->headScript ()->appendFile ( '//oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js', 'text/javascript', array('conditional' => 'lt IE 9') );
$this->_view->headScript ()->appendFile ( $this->_view->baseUrl ( '/assets/js/scripts.min.js?ver=1.0.0' ) );

这很有效,我在布局中得到了以下输出。

<!--[if lt IE 9]> <script type="text/javascript" src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script><![endif]-->
<!--[if lt IE 9]> <script type="text/javascript" src="//oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script><![endif]-->
<script type="text/javascript" src="http://om.localhost.com/assets/js/scripts.min.js?ver=1.0.0"></script>

上面的输出很好。但它建议我把条件脚本放在布局的头部,剩下的脚本放在正文的末尾。

有没有办法在ZF1中实现这一点?

附言:我试过使用占位符,但没有用。我不想在布局中对这些脚本进行硬编码。

谢谢你的帮助。

对于head部分,您可以像您的代码一样使用headScript()方法
在身体的末端,你可以使用InlineScript()方法,如下所示:

$this->view->InlineScript()->appendFile($this->view->baseUrl() .'/js/myfile.js');

在布局的末尾添加:

<?php
    echo $this->InlineScript(); 
?>

要在引导程序中添加脚本,可以执行以下操作:

protected function _initView()
{
    $options = $this->getOptions();
    if (isset($options['resources']['view'])){
        $view = new Zend_View($options['resources']['view']);
    }
    else{
        $view = new Zend_View;
    }
    $view->InlineScript()->appendFile(...);
}