在我的插件Super Static Cache的使用过程中,经常会有人问我这样的问题,怎么样让Super Static Cache插件支持我的HTML压缩插件,本文这里不谈技术实现问题,着重来分析一下现在的网站有没有必要再进行HTML代码压缩。
代码压缩压缩的是什么?
HTML的全称是超文本标记语言,HTML网页本身是一种文本文件,通过在文件中添加标记符,可以告诉浏览器如何显示其中的内容,包括文字大小,颜色,图片显示等等。这就意味着在文本文件中的一些特定意义的字符可以在浏览器显示的时候就不一样了,HTML代码压缩就是压缩这些在文本文件中有意义,但是在HTML中不显示的字符,包括空格,制表符,换行符等,还有一些其他意义的字符,如HTML注释也可以被压缩。
有了这个基础,我们挑选网络上的100张未经过HTML压缩的页面进行统计。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib2,re
import matplotlib.pyplot as plt
htmlsp = re.compile(r"[\r\n\t]")
def htmlcompress(html):
html = htmlsp.sub("",html)
return html.replace(" "," ")
urls = open("urls.txt","rb")
comdation = list()
while True:
url = urls.readline()
if not url:
break
if not len(url):
continue
try:
content = urllib2.urlopen(url).read()
except:
continue
unlen = len(content)
comlen = len(htmlcompress(content))
comra = 100.0*(unlen*1.0-comlen*1.0)/unlen
obj = "uncompress:%d bit, compress:%d bit, compressdatio: %f%%"%(unlen,comlen,comra)
print obj
comdation.append(comra)
plt.ylabel("compressdatio")
plt.plot(comdation)
plt.show()