網站性能優化之開啟服務器端http壓縮


公司的一個項目由於管理和開發方面的一些問題,導致開發完成之后,一個js文件變的很大,minimize之后還有700kb, 影響了網站的性能,特別是在網速慢的時候,加載一個頁面居然要2分鍾。招來了一大堆的客戶投訴。。。

解決這個問題最理想的辦法是分解這個超大js文件,只加載所需的javascript。但是由於最初的開發人員都已經不再了,這個分解任務風險系數太高,不能輕易嘗試(客戶要求很高,一旦出錯很難和客戶解釋)。為了提高在低網速下的網站反應時間,我想到了用服務器端壓縮http響應內容的辦法,以此來減少網絡數據傳輸。

IIS 7.0改進了服務器端壓縮的方法,使其更加容易配置和使用。

這里是微軟官方網站的一個詳細介紹和配置https://www.iis.net/configreference/system.webserver/httpcompression

IIS 7.0以及更高版本提供了2種壓縮方法:

1. 靜態壓縮:壓縮服務器端的靜態內容,如*.js,*.css等。它會降壓縮后的內容緩存到如下路徑:%windir%\inetpub\temp\IIS Temporary Compressed Files\ApplicationPool\

2. 動態壓縮:壓縮服務器端動態生成內容,如*.aspx等。開啟動態壓縮之后,服務器每次輸出動態內容之前都會進行壓縮,進而比較耗資源。

IIS 7.0以及更高版本支持2種壓縮方法:

1. Deflate: 壓縮率較Gzip更高,但除了瀏覽器之外,支持Deflate的平台並沒有Gzip多。

2. Gzip(GNU zip) : 推薦設置此種壓縮方法。

如何通過修改web.config來開啟Gzip壓縮

ApplicationHost.config是IIS 7.0之后引入的一個IIS配置文件,詳細內容參考官方鏈接http://www.iis.net/learn/get-started/planning-your-iis-architecture/introduction-to-applicationhostconfig

該文件的的位置%windir%\system32\inetsrv\config

http壓縮的相關配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    
    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" staticCompressionLevel="9" />
      <dynamicTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </dynamicTypes>
      <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="application/atom+xml" enabled="true" />
        <add mimeType="application/xaml+xml" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </staticTypes>
    </httpCompression>
    
    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    
  </system.webServer>
</configuration>

<httpCompression>節點用於配置靜態壓縮和動態壓縮,<urlCompression>則用於開關http壓縮。IIS 7.0默認開始靜態壓縮而關閉動態壓縮,IIS 7.5及之后版本則默認開啟靜態壓縮和動態壓縮。將urlCompression節點的doStaticCompression和doDynamicCompression屬性設為true即為開啟壓縮。在設置完成之后,重啟IIS,之后去前台測試,發現700KB的js文件壓縮到了300KB,效果還是不錯的。

需要注意的是,ApplicationHost.config里面的配置是IIS的全局配置,會影響所有的網站。如果只想為某個網站開啟http壓縮,可通過修改ApplicationHost.config下httpCompression配置,將overrideModelDefault屬性設置Allow,允許它在每個網站的web.config里面重新配置(urlCompression默認已經允許在web.config里重新配置)。

<section name="httpCompression" allowDefinition="MachineToApplication" overrideModeDefault="Allow" />

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM