Home Backend Development PHP Tutorial 使用PHP的GZip压缩功能对网站JS和CSS文件进行压缩加速网站访问速度

使用PHP的GZip压缩功能对网站JS和CSS文件进行压缩加速网站访问速度

Jun 20, 2016 pm 01:03 PM
css compression

现在大量的WEB 2.0网站为了追求用户体验,就会大量使用CSS和JS文件。这就导致在服务器带宽一定的情况下,多用户并发访问速度变慢。如何加快网页响应速度?本篇文章主要是介绍一下使用PHP对JS和CSS进行压缩处理的方法,在这里假设服务器仅支持GZIP压缩,不支持.htaccess(符合很多站长的租用的虚拟主机实际情况)的情况。

首先说说对CSS和JS文件进行性能优化的几个小技巧:

 
(1)将多个CSS/JS文档合并成一个文件,以减少HTTP请求
 
(2)对合并后的文件进行文档压缩,比如分别使用js compressor和CSS compress
 
(3)如果使用到一些主流的JavaScript框架,比如JQuery, Mootools或者YUI,强烈推荐直接使用Google AJAX Library以外部链接的形式导入基库。最后,就是本文所提到的,使用GZIP在服务器端对JS/CSS文档进行压缩。实际上,用PHP使用GZIP压缩非常简单,其核心是使用ob_gzhandler,不过需要注意的一点是,并不是所有浏览器都支持GZIP传送到客户端的数据,所以要进行一定的容错处理。
 
下面是使用PHP通过GZIP压缩CSS的实例。
 

在存放CSS的文件夹中新建一个style.php文件,在此文件中加入以下代码:

<p><?php</p>if(extension_loaded('zlib')){//检查服务器是否开启了zlib拓展<br />	ob_start('ob_gzhandler');<br />}<br />header('content-type: text/css; charset: utf-8');//注意修改到你的编码<br />header('cache-control: must-revalidate');<br />$offset = 60 * 60 * 24;//css文件的距离现在的过期时间,这里设置为一天<br />$expire = 'expires: ' . gmdate('D, d M Y H:i:s', time() + $offset) . ' GMT';<br />header($expire);<br />ob_start('compress');<br />function compress($buffer) {//去除文件中的注释<br />	$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);<br />	return $buffer;<br />}<br />//包含你的全部css文档<br />include('global.css');<br />include('layout.css');<br />if(extension_loaded('zlib')){<br />	ob_end_flush();//输出buffer中的内容,即压缩后的css文件<br />}<br /><p>?>
Copy after login

如果你处理的是JavaScript文件,你需要将上面代码中的第5行的Content-type修改成以下:

header('content-type:application/x-javascript; charset: utf-8');
Copy after login

修改完成之后,引入相关需要的CSS文件,然后再原HTML引入CSS的地方相应的替换为如下的引入方式:

<link rel="stylesheet" media="screen" href="style/css.php?v=100415" />
Copy after login

同理JS引入方式如下:

<script type="text/javascript" src="js/js.php?v=121"></script>
Copy after login

由于上面代码中使用到了HTTP的Expires(过期)属性用于在客户端缓存CSS/JS代码,所以,如果过期时间设置的太长(比如一 年),当你在服务器端修改了JS/CSS代码时,客户端可能不会立即生效。

解决办法是:在php文件后面添加一个随机参数,如上面例子中的v=121,当下次修改了文件时,记得相应修改此随机参数(比如修改为122)即可。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles