Minify js và css


Đây là việc tích hợp thư viện htmlminify, kết hợp với thư viện zend view helper tự viết. Tác dụng của nó là ghép, cache các file js, css lại thành một, tăng tốc độ tải trang

– Đầu tiên, download thư viện minify ở đây http://code.google.com/p/minify/ và đặt vào folder chứa file index.php trong project.

– Xây dựng lớp chứa hằng số Nc_Constant như sau

Mã: Chọn tất cả
<?php

class Nc_Constant {
const SITE_BASE_URL = "http://localhost/trangtin";
const SITE_BASE_URL_PATH = "trangtin";
}

– Kế tiếp, xây dựng lớp Nc_View_Helper_Css như sau

Mã: Chọn tất cả
<?php

class Nc_View_Helper_Css {

protected $view;
protected $paths = array();

public function Css() {
return $this;
//$this->view->headLink()->appendStylesheet(Nc_Constant::SITE_BASE_URL . $path);
}

public function add($path){
$this->paths[] = Nc_Constant::SITE_BASE_URL_PATH . $path;
}

public function min(){
$this->view->headLink()->appendStylesheet(Nc_Constant::SITE_BASE_URL .'/min/?f='. implode(",", $this->paths));
}

public function setView(Zend_View_Interface $view) {
$this->view = $view;
}

}

– Xây dựng lớp Nc_View_Helper_Js như sau

Mã: Chọn tất cả
<?php

class Nc_View_Helper_Js {

protected $view;
protected $paths = array();

public function Js() {

return $this;
//$this->view->headScript()->appendFile(Nc_Constant::SITE_BASE_URL . $path);
}

public function add($path){
$this->paths[] = Nc_Constant::SITE_BASE_URL_PATH . $path;
}

public function min(){
$this->view->headScript()->appendFile(Nc_Constant::SITE_BASE_URL .'/min/?f='. implode(",", $this->paths));
}

public function setView(Zend_View_Interface $view) {
$this->view = $view;
}

}

Vậy là OK rồi. Chỉ cần sử dụng nữa là được.
Trong file view chỉ cần gọi

Mã: Chọn tất cả
<?php $this->css()->add('/public/css/style.css'); ?>
<?php $this->css()->add('/public/css/skin.css'); ?>
<?php $this->css()->add('/public/css/jquery-ui-1.8.16.custom.css'); ?>

<?php $this->js()->add('/public/js/jquery-1.7.1.min.js'); ?>
<?php $this->js()->add('/public/js/jquery.jcarousel.min.js'); ?>
<?php $this->js()->add('/public/js/jquery-ui-1.8.16.custom.min.js'); ?>
<?php $this->js()->add('/public/js/ads.js');?>

// chú ý phải có dòng này nữa
<?php $this->css()->min();?>
<?php $this->js()->min();?>

Tada, vậy là xong rồi, các bạn có thể thực hiện và kiểm nghiệm kết quả

Nguồn : http://www.zend.vn/forum/viewtopic.php?f=87&t=2955

 

Bình luận về bài viết này