As we all know, one thing which mainly slow down our site is the plenty of css and js files. But very often we have to make them seperate from each other in order to facilitate management.
The problem we met in day-to-day practice is that, it’s more faster to send one file which is 50k then to send one file with 10k for 5 times. This is because the http request is very very expensive.
When we come to Zend Framework the layout and view helper can be helpful to reduse the numbers of http request for css and js files.
Let’s take an example now for css (js is more or less the same) :
class Kbs_View_Helper_Css extends Zend_View_Helper_Abstract { // Container for css files protected $_container = array(); // Return self object public function css() { return $this; } // Push into container public function append($value) { array_push($this->_container, $value); return $this; } // Prepend to container public function prepend($value) { array_unshift($this->_container, $value); return $this; } // Return very similar to 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; } }
[/codesyntax]
We use it in layout then :
<?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>
[/codesyntax]
You can use it anywhere you want to import css. For example in indexAction :
$this->view->css()->append('index.css');
[/codesyntax]
We now reduse the numbers of request and send multi-css at one time.