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

现在大量的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>?>

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

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

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

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

同理JS引入方式如下:

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

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

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


Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software