Bookmark and Share

Lee's 程序人生

HTML CSS Javascript XML AJAX ATLAS C# C++ 数据结构 软件工程 设计模式 asp.net Java 数字图象处理 Sql 数据库
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

用 View Helper 为单个请求同时发送多个 css 或 js 文件

Posted on 2010-02-05 19:53  analyzer  阅读(374)  评论(0编辑  收藏  举报

众所周知,大量的 css 及 js 文件是影响网站速度的最主要原因之一。而且很多时候我们又不得不把它们分开来以便管理。

 

然而我们通过日常的实践,发现分5次发送10k的文件的速度,要远慢于一次性发送50k的文件,原因正在于 http request 请求是非常昂贵的。

 

在 Zend Framework 中,我们可以结合 layout 及 view helper 来做一些优化工作,以尽量减少 http request 请求 css 或 js 的次数。

 

下面是一简单的 css 助手(js的类似) :

 

class Kbs_View_Helper_Css extends Zend_View_Helper_Abstract
{
    // 用来保存需要发送的css文件名
    protected $_container = array();
 
    // 返回自己
    public function css()
    {
        return $this;
    }
 
    // push入队列
    public function append($value)
    {
        array_push($this->_container, $value);
        return $this;
    }
 
    // 安插在队头
    public function prepend($value)
    {
        array_unshift($this->_container, $value);
        return $this;
    }
 
    // 返回类似的 html link :
    // <link rel="stylesheet" type="text/css" href="/public/css/css.php?f1=default.css&f2=other.css&" />
    public function __toString()
    {
        $html = '';
 
        if (!empty($this->_container)) {
            $href = $this->view->pathCss . 'css.php?';
            $i = 0;
            foreach ($this->_container as $item) {
                $i++;
                $href .= "f$i=$item&";
            }
            $html = '<link rel="stylesheet" type="text/css" href="'.$href.'" />';
        }
 
        return $html;
    }
}

 

在 layout 中我们可以这样用 :

 

<?php
// layoutDefault.phtml
$this->css()->prepend('default.css');
$this->css()->append('other.css');
?>
<html>
 
    <head>
        <?php
        echo $this->headTitle();
        echo $this->headMeta();
        echo $this->headLink();
        echo $this->css();
        echo $this->headStyle();
        ?>
    </head>
 
</html>

 

当然你可以在任何地方调用类似 $this->view->css() 来加载你需要的 css 文件,例如在 indexAction中 :

 

$this->view->css()->append('index.css');
 

 

这样就能在一个请求中同时发送多个文件,从而大大减少 http request 请求次数。

 

转自:http://kbs.kimbs.cn/blog/list/post/14/title/sending-multi-css-and-js-files-in-one-file-for-one-request 

我要啦免费统计