众所周知,大量的 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 请求次数。