部署內嵌圖片


第一部分 – 第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+qyBNReqJWR8SPl8RWPK8ZtHGcJiCqOsnJfiD8cb9vqsgQ0NjdqYBNzIEZRUFlgCThef9z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96ye0fPptk9lQPQA3ayN2WAKzBDmGjJDyun8RYdr8DdvbnzTjsKggiCPokt5XblWlDaWbtRzvxOAHZtzTKDv8r42EMIh8j8m59DH77y87mVrKjjFb7O/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