HTML輸出最小化對於減少頁面加載時間和減小頁面總大小對於提高網站性能非常重要。壓縮HTML輸出還可以減少請求站點的用戶的數據使用量。
縮小可以通過刪除不必要的細節並消除多餘的空格,換行符,註釋等來實現。但是,縮小會降低代碼的可讀性。縮小可以將文件大小最多減少70%。PHP用於將文件從開發環境傳輸到生產環境。HTML文件可以手動和自動縮小。可以使用幾種在代碼中添加空格的工具來取消縮小。但是,縮小期間刪除的所有註釋都無法恢復。
示例:這是不壓縮代碼的HTML文件。
HTML output minification is important to improve website performance by reducing the page load times and reduce the overall page size. Minifying HTML output also reduces the data usage of the user requesting the site.
Minification can be done by removing unnecessary details and eliminating excessive whitespaces, newlines, comments, etc. However, minification reduces the readability of the code. Minification can reduce file size upto 70%. PHP is used to transfer files from development to production environment. HTML files can be minified both manually and automatically. Minification can be undone using several tools that add whitespaces in the code. However, any comments removed during minification cannot be restored.
Example: This is the HTML file without minifying the the code.
HTML file after minification
<html><head><title>Title Page</title></head><body><h1>Hello world!</h1></body></html>
Approach 1: Using GZip Compression in Apache:
Steps to enable Gzip Compression in Apache
- Open the Apache configuration file
vim /etc/httpd/conf/httpd.conf
- Check the following line in the configuration file.
LoadModule deflate_module modules/mod_deflate.so
- Add the following lines at the end of configuration file.
AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript
- Restart the Apache Server
sudo service httpd restart
方法2:可以使用帶回調的ob_start()函數來最小化HTML代碼。
Approach 2: HTML code can be minified with ob_start() function with a callback.ess_4
Output:
<!DOCTYPE html><html><head><title>Demo for minifier</title></head><body><h1>Hello World</h1></body></html>
方法3:使用HTMLMinifier插件: HTML Minifier是服務器端源代碼縮小器,旨在通過消除不必要的空格,註釋和換行符來優化發送給客戶端的HTML,CSS和JavaScript輸出。HTMLMinifier在插件中提供了多種優化選項,可以根據用戶要求進行選擇。
使用HTMLMinifier的步驟:
- 從https://www.terresquall.com/download/HTMLMinifier.php下載HTMLMinifier文件
Approach 3: Using HTMLMinifier plugin: HTML Minifier is a server-side source code minifier designed to optimise HTML, CSS and JavaScript output sent out to the client by removing unnecessary whitespaces, comments and newlines. HTMLMinifier offers a variety of optimisation options in the plugin that can be selected as per the user requirement.
Steps to use HTMLMinifier:
- Download the HTMLMinifier file from https://www.terresquall.com/download/HTMLMinifier.php
- Include the following code into the php file
- Run the php file
沒有留言:
張貼留言