Data URL和圖片(前端細節優化)
技術標籤:html
Data url
1. 對比傳統的圖片和data url
首先在html中嵌入圖片,我們通常使用標籤
用在伺服器上的相對路徑請求圖片
例如:
<img src="img/123.jpg">
但是通過data url,我們可以把123.jpg轉換成base64字串,然後再嵌入到標籤中
例如:
這張圖片的base64為
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHYAAABhCAYAAAADdFUyAAAACXBIWXMAABJ0AAASdAHeZh94AAAAEXRFWHRTb2Z0d2FyZQBTbmlwYXN0ZV0Xzt0AACAASURBVHic5Z13nFXV1fe/+5xzz+13+gwgMIMUOxoFFETMa0sUFbuIJaa8xvY8seSTRI0JYk3UGEt8Us2T10IUkwiiIgIiTSyogIIU2wgDA9Nnbr/n7PePfc/0cu8wDAOuz8ePM8PeZ6+z1/nttfZaa68tRpaWSVqTlGB4QNMhGVG/C0G3JG3QXKpfKgZ2quc+SECAywe2pfr12Cc9lu4GlwnxsPpdaBnwp4PLj0zG8OgC0+MhlkyQSiaRltX52NIG06dYTUbSbTKYi6z5k4AETwisJCQiit+eyLYUf5oB8Sb1t/R7tB2xvVDJRKiynVCTmfXprVANEwy3evlMJ03oagJSMbDiSCEQQomo81Gl6ufyqxbZCLU3/AG4g70Tqu6CeKP6W6s5bBm1M6Rm8iKa0Q6pPbyI87H0FqmGGxJNqm9GSNXA9EMqAVYchIaUdlrgIIRAdugnwfQqXhPh7JCaFX8OUoNq7nqD1Fgj6Rdp00RrHuBAR2oqrn7vvtN+j1SHtG8SUh2ypURK0HUDKVvh9QBAqkPaNxKp0nm8RGgaBxJSHdK+SUhtbtasX9M/c+Ag1SHtG4VUpykSKSWaph1wSHX4075JSO3An7TB5VG/HiBIdWSlfZOQCmp7Y9s2SNBMR6gHDlLRdDD9dM/VAYxUafpBuFrxd2AgFTMAiaZuBHuAITXdCaREmj7ldUpG9y5/0O9IJREG2+pCsAckUknvU/1Iy0bGGtEMHeSBhVRHVp3tBQ5YpCrrF0hGlDylRGjd8LkfItXhT+vY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3f86l9oVO77YPo9jJnraXhfhZP3cN6v80LcIfA9d45S9Mlf13EU7sdS3QvVID/D+x7sq5IP2knAAAAAElFTkSuQmCC
你只需要在瀏覽器中輸入這個字串,就可以訪問到圖片,也就是說這個字串已經包含了圖片的所以資訊,只不過使用字串的資訊表示。
所以在標籤中,我們可以這樣使用
<img src="這裡為base64編碼">
大家可以在這裡試試:http://tool.chinaz.com/tools/imgtobase/,把圖片轉base64。
2. data url優缺點
優點:
- 用於小圖片,因為一個圖片佔用一個HTTP請求不合適
- 當訪問外部資源很麻煩或受限時
- 當圖片是在伺服器端用程式動態生成,每個訪問使用者顯示的都不同時。
缺點:
- Base64編碼的資料體積通常是原資料的體積4/3,也就是Data URL形式的圖片會比二進位制格式的圖片體積大1/3
- Data URL形式的圖片不會被瀏覽器快取,這意味著每次訪問這樣頁面時都被下載一次。這是一個使用效率方面的問題——尤其當這個圖片被整個網站大量使用的時候。
3. 疑問
當第一次看到Data URL的作用和用法時,你也許會很不疑惑,“為什麼要麻煩的將圖片轉換成base64編碼字串,還要嵌入的網頁中,將HTML程式碼弄的混亂不堪,甚至還會有效能上的問題。”
誠然,無法否認快取在瀏覽器效能中的重要作用——如何能將Data URL資料也放入瀏覽器快取中呢?**答案是:通過CSS樣式檔案。**CSS中的url
操作符是用來指定網頁元素的背景圖片的,而瀏覽器並不在意URL裡寫的是什麼——只要能通過它獲取需要的資料。所以,我們就有了可以將Data URL形式的圖片儲存在CSS樣式表中的可能。而所有瀏覽器都會積極的快取CSS檔案來提高頁面載入效率。
(當我看到這裡的時候感覺真的太妙了)
假設我們的頁面裡有一個很小的div
元素,我們想用一種灰色的斜紋圖案做它的背景,這種背景在當今的網站設計者中非常流行。傳統的方法是製作一個3×3畫素的圖片,儲存成GIF或PNG格式,然後在CSS的background-image
屬性中引用它的地址。而Data URL則是一種更高效的替代方法,就像下面這樣。
css檔案
.striped_box
{
width: 100px;
height: 100px;
background-image: url("data:image/gif;base64,R0lGODlhAwADAIAAAP///8zMzCH5BAAAAAAALAAAAAADAAMAAAIEBHIJBQA7");
border: 1px solid gray;
padding: 10px;
}
html檔案
<div class="striped_box lazy ">
這是一個有條紋的方塊
</div>
4. 總結
原文作者講的很透徹,推薦大家去看看2014年的這篇部落格:https://www.iteye.com/blog/justcoding-2090964
到了這一步想必在前端鑽的應該挺深了,考慮的是各種優化網站,受益匪淺。