现代浏览器可以基于RFC 2397标准使用base64把图片进行编码,然后输出类似data:image/png;base64,iVBORw0KGgoAA…。的文本即可。 RFC 2397标准制定与1998年,至今IE6、7仍不支持,如果想要实现文本携带图像数据,俄罗斯某大侠写了这么一篇文章:http://webo.in/articles/habrahabr/46-cross-browser-data-url/
文章指出可以利用mhtml协议方式把含有图片数据mht格式的文件链接进来,这个mht格式数据可以写到css、html或者js的注释中,引用的时候直接链接即可。
关于mht格式在百度百科中的定义:
mht是一种WEB电子邮件档案,能用浏览器打开的前提是你的机子上必须装有Outlook Express !在我们点菜单-》文件-》另存为…后在选择保存类型时可以看到有这一项,其最大优点是所保存的网页只有一个文件,便于管理。而以 (*.htm;*.html)保存的网页,你会看到其实有一个网页和相应的一个文件夹,IE把页面元素分开存放了。说白了,该文件就是你从浏览器中看到的网页的全部。
MHT叫“web单一文件”。顾名思义,就是网页中包含得图片,CSS文件以及HTML文件全部放到一个MHT文件里面。mht就是mono html,就是独立的HTML文件,他是IE在save as时将页面中所有可以收集的元素全部存放在一个页面里,当然尺寸就大了啦,不过倒省却了相对路径绝对路径的烦心事。
下面我把“李小龙”的一张图片经过base64编码后嵌入javascript,例如:
/*
Content-Type: multipart/related; boundary="_ANY_STRING_WILL_DO_AS_A_SEPARATOR"
--_ANY_STRING_WILL_DO_AS_A_SEPARATOR
Content-Location:%E5%94%90%E6%96%8C
Content-Transfer-Encoding:base64
iVBORw0KGgoAAAANSUhEUgAAAPAAAACJCAMAAAAlpkWpAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACRQTFRF5+vt1s+9yql2joyHb2tjIyAj0rOBcVQ1oIFXSzsuy8GurayofdFEagAADapJREFUeNrsneli46oOgFlkQPD+73u1sNmx0ywnrpu5/JjpTNM0X7QLQczyjy3zDwLbiyz/7Gsvz/+OPw2M9h8Dhv8Dfzlw+QpglD8Qf+b19iuAARZM2dr0E2+03wGcUnTGGBvSByz4ksDBBQJ2LsC/ApwtS9g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Zy2P/xuFvpIaDr0WlkuBI3+vM20J1Z5lZfb+Mfug3cdrb0iML4MfEfEt+sywPl1XhJx/nvAr1ow/qDTVwV+2YKl0n1Cp68C/LIFy22BAPmPAfs3PJYAl78F/JbHIuWA+MeAYXlr8S7KnwLOy9vA8BTwP/cp8f/W+p8AAwBcNiMCbK0DdAAAAABJRU5ErkJggg==
*/
(function () {
var doc = document,
isMhtml = !-[1,] && !('prototype' in Image),
url = doc.getElementsByTagName('script'),
ajax = function (url, fn){
var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function(){
XHR.readyState === 4 && XHR.status === 200 && fn(XHR.responseText);
};
XHR.open('GET', url, 1);
XHR.send(null);
},
setStyle = function (content) {
var style = doc.createElement('style');
doc.getElementsByTagName('head')[0].appendChild(style);
style.styleSheet && (style.styleSheet.cssText += content) || style.appendChild(doc.createTextNode(content));
};
url = url[url.length - 1].getAttribute('src', 4);
isMhtml ? setStyle('.dataUrlScheme{*background-image:url("mhtml:' + url + '!%E5%94%90%E6%96%8C")}') :
ajax (url, function (data) {
data = '/upload/users/1/20131206/png;base64,' + data.split('base64\r\n\r\n')[1].split('\r\n')[0] + '")}';
setStyle(data);
});
})();
我原来尝试使用js把MHT动态写入HTML文件中再引用页面地址,可是未能成功,所以只能静态嵌入到js文件中。
好了,是否这个例子值得jser无限遐想呢,或者又留下了什么遗憾呢?DEMO地址:
http://www.planeart.cn/demo/dataUrlScheme/
(兼容IE6/IE7/IE8/。。/Firefox/Chrome/Oprea/Safari 注意IE不能用IETeste调试)
base64在线转换地址:http://www.pjhome.net/web/html5/encodeDataUrl.htm
planeArt.cn原创文章,原文地址:http://www.planeart.cn/?p=1192