search
HomeCMS TutorialWordPressHow to optimize wordpress blog

How to optimize wordpress blog

Nov 15, 2019 am 10:52 AM
wordpress

How to optimize wordpress blog

wordpress博客怎么优化?

我的优化步骤是:

1.压缩CSS和JS文件,并修改一部分插件,优化页面的载入进程

一般需要另外加载JS或者CSS的插件都会存在add_action(”wp_head”,”xxxx”)或者add_action(”wp_footer”,”xxxx”)这两句代码,目的是把自己的脚本或者样式插入到主题的wp_head()和wp_footer()处,使插件可以正常工作(那些反映说插件激活了但看不到效果的人注意了,我观察到相当一部分人所使用的主题不能正常加载插件的脚本,缺的就是这两个函数了)。

下面转回正题。我们需要优化载入进程,也就是流量整形,把CSS文件移到head里(这点100%的插件都能做到,不用担心),把JS文件放在页面最后。我们可以把add_action(xxxx)这句删掉,然后手工把所需的文件插入到主题模板里。

推荐:《WordPress教程

2.压缩CSS和JS,缩短文件的加载时间

经常用jQuery写脚本的人应该比较清楚,未压缩版的jQuery库(1.3.2)大小为120K左右,但min版的只有56K。因为jQuery库min版经过YUI Compressor压缩,去除了代码里的注释、无用的空格和换行符。我们也可以用YUI来压缩一下自己的脚本,压缩率能达到30%~70%。由于软件版的YUI安装过程比较复杂,这里有个在线版。

而CSS的压缩就比较简单,就是去除换行符、空格和注释,大家可以用在线工具压缩一下。但主题的style.css头部被注释掉的主题信息不能删掉,否则可能导致主题不正常。

对于CSS的压缩,很多人用的PHP压缩。编写名为style.css.php的文件,内容如下:

代码如下:

if ( extension_loaded('zlib') and !ini_get('zlib.output_compression') and ini_get('output_handler') != 'ob_gzhandler' and ((version_compare(phpversion(), '5.0', '>=') and ob_get_length() == false) or ob_get_length() === false) ) {
ob_start('ob_gzhandler');
}else{
ob_start();
}
//检查是否含有Gzip相关模块,有的话就采用Gzip传输,如果主机有Apache mod_deflate.c或其它等效模块的话,可以不写这段
@header("Cache-Control: public");
@header("Pragma: cache");
//缓存文件
$expiresOffset = 3600*24*365;
@header( "Vary: Accept-Encoding" );
@header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
//设置缓存时间
@header('Content-Type: text/css');//声明文件类型
$cssdata = file_get_contents('style.css');//读取style.css的内容
$cssdata = preg_replace(array('/\s*([,;:\{\}])\s*/', '/[\t\n\r]/', '/\/\*.+?\*\//'), array('\\1', '',''), $cssdata);//清除注释和换行符等
echo $cssdata;//输出代码

把这个文件放在主题文件夹里,并把主题CSS的加载代码改为

代码如下:

<link rel="stylesheet" href="<?php bloginfo(&#39;stylesheet_directory&#39;); ?>/style.css.php" type="text/css" media="all" />
</link>

当然JS文件也可以用PHP进行优化,但由于通常情况下加载的JS文件比较多,我通过另一个文件来间接加载JS。建立一个名为js.php的文件,内容如下:

代码如下:

if ( extension_loaded(&#39;zlib&#39;) and !ini_get(&#39;zlib.output_compression&#39;) and ini_get(&#39;output_handler&#39;) != &#39;ob_gzhandler&#39; and ((version_compare(phpversion(), &#39;5.0&#39;, &#39;>=&#39;) and ob_get_length() == false) or ob_get_length() === false) ) {
ob_start(&#39;ob_gzhandler&#39;);
}else{
ob_start();
}
//同样是Gzip压缩的语句
$js_folder = "js/";//JS文件所在目录,相对路径
$js_src = urldecode( htmlspecialchars( $_GET[&#39;src&#39;] ) );//获取JS文件名
$js_file = $js_folder.$js_src;//JS文件位置
@header("Cache-Control: public");
@header("Pragma: cache");
//缓存文件
$expiresOffset = 3600*24*365;
@header( "Vary: Accept-Encoding" ); // Handle proxies
@header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
//设置缓存时间
@header(&#39;Content-Type: text/javascript; charset: UTF-8&#39;);//声明文件类型
$jsdata = file_get_contents($js_file);
echo $jsdata;
//输出内容

把这个文件放在主题目录下,在主题文件夹里建立一个JS文件夹,把所需的JS文件都放到这个文件夹里。改写一下主题,用以下方式加载JS文件:

代码如下:

<script type="text/javascript" src="<?php bloginfo(&#39;stylesheet_directory&#39;); ?>/js.php?src=library.js"></script>

如果你的主机有Apache mod_deflate.c模块,基本上可以忽略上面的方法,因为只需要在.htaccess文件里加入以下代码就可以实现全站Gzip传输了。而且压缩率更高。

代码如下:

<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-httpd-php application/x-javascript
</ifmodule>

3.整合CSS和JS文件

经过上面一番折腾以后,其实页面载入速度已经快很多了,但速度是没有止境的,我们追求更快。搞无可搞以后,只能从减少HTTP请求数下手了,这一步的目的尽量整合所有的CSS和JS。

整合CSS比较简单,用各种主流浏览器测试几个页面,没发现框架错位现象,把相关的CSS里的代码粘贴到style.css里,并把相关的CSS-image也复制到主题目录下,修改一下CSS里的图片路径就行了。

JS的整合方法则复杂点,要搞清楚那些脚本需要在对象加载前加载,否则是无效的,并且要注意不同插件的JS冲突问题。

整合完CSS和JS后,重返第一步,把插件里加载脚本和样式的语句删掉。

The above is the detailed content of How to optimize wordpress blog. For more information, please follow other related articles on the PHP Chinese website!

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
How does WordPress's plugin ecosystem enhance its CMS capabilities?How does WordPress's plugin ecosystem enhance its CMS capabilities?May 14, 2025 am 12:20 AM

WordPresspluginssignificantlyenhanceitsCMScapabilitiesbyofferingcustomizationandfunctionality.1)Over50,000pluginsallowuserstotailortheirsiteforSEO,e-commerce,andsecurity.2)Pluginscanextendcorefeatures,likeaddingcustomposttypes.3)However,theycancausec

Is WordPress suitable for e-commerce?Is WordPress suitable for e-commerce?May 13, 2025 am 12:05 AM

Yes, WordPress is very suitable for e-commerce. 1) With the WooCommerce plugin, WordPress can quickly become a fully functional online store. 2) Pay attention to performance optimization and security, and regular updates and use of caches and security plug-ins are the key. 3) WordPress provides a wealth of customization options to improve user experience and significantly optimize SEO.

How to add your WordPress site in Yandex Webmaster ToolsHow to add your WordPress site in Yandex Webmaster ToolsMay 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to fix HTTP image upload errors in WordPress (simple)How to fix HTTP image upload errors in WordPress (simple)May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to fix the issue where adding media buttons don't work in WordPressHow to fix the issue where adding media buttons don't work in WordPressMay 12, 2025 pm 09:00 PM

Recently, one of our readers reported that the Add Media button on their WordPress site suddenly stopped working. This classic editor problem does not show any errors or warnings, which makes the user unaware why their "Add Media" button does not work. In this article, we will show you how to easily fix the Add Media button in WordPress that doesn't work. What causes WordPress "Add Media" button to stop working? If you are still using the old classic WordPress editor, the Add Media button allows you to insert images, videos, and more into your blog post.

How to set, get and delete WordPress cookies (like a professional)How to set, get and delete WordPress cookies (like a professional)May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to Fix WordPress 429 Too Many Request ErrorsHow to Fix WordPress 429 Too Many Request ErrorsMay 12, 2025 pm 08:54 PM

Do you see the "429 too many requests" error on your WordPress website? This error message means that the user is sending too many HTTP requests to the server of your website. This error can be very frustrating because it is difficult to find out what causes the error. In this article, we will show you how to easily fix the "WordPress429TooManyRequests" error. What causes too many requests for WordPress429? The most common cause of the "429TooManyRequests" error is that the user, bot, or script attempts to go to the website

How scalable is WordPress as a CMS for large websites?How scalable is WordPress as a CMS for large websites?May 12, 2025 am 12:08 AM

WordPresscanhandlelargewebsiteswithcarefulplanningandoptimization.1)Usecachingtoreduceserverload.2)Optimizeyourdatabaseregularly.3)ImplementaCDNtodistributecontent.4)Vetpluginsandthemestoavoidconflicts.5)ConsidermanagedWordPresshostingforenhancedperf

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 Article

Hot Tools

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools