部署内嵌图片


第一部分 – 第13章

Image

当网站页面必须显示一张图片时,就必须得用一个http请求来获取该图片文件。用来将图片加载至网页的经典HTML代码列示如下:

<body>
  <img src="http://www.mobilewebsitebook.com/images/logo.png">
</body>

Base64

在不使用http请求情况下将图片文件加载到网站页面上也是可以的。通过Base64编码,你可以将图片内嵌到网站页面的HTML代码中。如下显示了应该如何以Base64格式包括该图片:

<body>
  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTFH80I3AAAKPElEQVR4Xu2b+VNWZRTHnZyaFqspsz3NzEyzzbIms1EzM9MmS62srLHNsmUqK0tNUUDZRMEFUVAWUVndAFHAFURckEUBERH8R059jvM83ve+bw6LzPuS/PCd995z7n3ufb73Oec55zzP2+PSpUsCzjSekUNnDl1TNDQ1aNuBDEvAoj2L5IGIB2RswthrgociH5L08nSvBwYaPAiYtnmavJ/6vkzfMl1mZc2Soqoirxtai0+2ftL1CBi+drhEF0dLyN4Q/e0IXln3StcjYGjsUPlj9x/XBM+ufrZrmkD2iWxZkLfAAmd2sOagZB3PahPGJY6ToD1BPnX7q/d7vYi/4EXA7ordElYYZnG64bQMWjlInlj5hP52FP2W95O+UX29XsRf8CIgsihSRqwbYbHz1E598c1lm3VEcN3MjJleDbUWeRV5gU1A1fkqj7n8QvMFJeDH7T/Kzzt+lu9zvpfvsr+Tv3L/ahdmps8MbAKWFCyRIbFDLHad2qUEfLTlI53anBi/cbzcHnq7l/xqeGvTW4FNgFNpAAHnms7JvNx5Gh+A4L3BSk7/6P6ScyLHyn1hz+k9tq2ANwGn0gACGi42qFfHFEB4YbglAD9h5L5QWFVo2+qyBNReqJWR8SPl8RWPK8ZtHGcJiCqOsnJfiD8cb9vqsgQ0NjdqYBNzIEZRUFlgCThef9zKfaGmsca2FdAEvJvyr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N2WAKzBDmGjJDyun8RYdr8DdvbnzTjsKggiCPokt5XblWlDaWbtRzvxOAHZtzTKDv8r42EMIh8j8m59DH77y87mVrKjjFb7O/tV+djhNJ4os4dxKAuUGWmbZBQBEAXlv/mq32UPhwFkANCI8ptR2rO6YLJW7fgHNjbQFfYAiAILJKE0MY+J0AQlwCKBB/JF6ein1KvxTAJFhic983Y9sMWVywWIexc8YxYHQwkrB1QwARKubhdpp+J+CmJTfpXA9uXHKj2jG2T/pL2OvrPhZX+PcKRVX3CDIg+CLAggBKcOx3ptLsrCcAvxNgojqAx6YoYpIeCHBPaYB8n9Uj7mdYu/UMdwI0ag4QQBzBaPg7/291ls5ZIuB8AEEMoTTHZIaExE49oMrMv1TwAVSV3cMaInsv661ypxOETFJ2slhzbcARgJPCq3O8cM9C9RHOUcDL8wdPIxuTMEZHg9Fj/yRMJmJ0EgCIFzA3Ksmc+50AvqD5wzVTHl79yJnL1WS+ILnFsDXDdIWJjjCHO/+DREzArDAldYrm+RDC9aZu4CYAMNOYv/75lQDWDJ3/LCGFJjp0XoO9MjtQIyDSY3g79YACTMi+EHWOtOOMFvED5CPO69mtyhpEU0uT/APpWzS9XrEGKAAAAABJRU5ErkJggg==" />
</body>

使用了大量小型图片(比如超过20)的移动网站页面应该部署Base64编码。这将明显减少http请求的数量。

Base64编码工具

可以使用如下工具将图片编码为Base64格式:

  • base64encode.net/base64-image-encoder

Base64的缺点

  • 当通过Base64实施内嵌图片时,一个不足之处就是网站浏览器将不会缓存这些图片。
  • Base64编码的图片通常比原始图片文件要大一些。例如,一个2KB的图片文件可能最后超过2.5KB。当你的图片文件超过5KB时,建议不要使用base64编码。


移动网站性能技术白皮书在2017年3月正式出版。

英文版:Implement Inline Images – 繁体中文版:部署内嵌图片







移动网站性能技术白皮书上的内容按下列许可协议发布: CC Attribution-Noncommercial 4.0 International

Gordon Choi's Mobile Website Book