也許你看到這個(gè)標(biāo)題第一個(gè)想法就是从隆,這不是 h5 同事去做的事嗎,直接給個(gè) url 地址寿烟,我們直接加載就行了辛燥。但是這個(gè)是根據(jù)業(yè)務(wù)情況來的,很多情況下加載的是 html 的代碼片段徘六,而不是 url地址榴都。
在我們項(xiàng)目中,很多情況是課程的介紹還有文章的詳情都是加載的Html 片段竿音。在后臺(tái)管理系統(tǒng)編輯的時(shí)候通過通用的插件使其插入圖片及其他元素阳惹,存在數(shù)據(jù)庫里的時(shí)候就是其里面的一個(gè)字段莹汤。展示如下圖:
優(yōu)化開啟
因?yàn)槭莾蓚€(gè)安卓跟 IOS 端都要優(yōu)化,IOS 同事仿微信圖片懶加載先做的差不多了逗旁,我這邊又在其基礎(chǔ)上做了些優(yōu)化舆瘪。安卓的話搜的資料倒不是很多,好在跟 IOS 都異曲同工吧算是淀衣。
先說一下實(shí)現(xiàn)思路吧:
本地加載基于 jquery的懶加載的 js 文件召调,加載進(jìn)行展示
相關(guān)文件如下:
下載地址:https://github.com/xinghedazhan/lazyload/tree/master
將兩個(gè) js 文件放在項(xiàng)目目錄的assets目錄下
因?yàn)榧虞dHtml 的代碼片段是自己添加網(wǎng)頁的頭跟尾的某残,所以在頭里面添加兩個(gè) js 文件的引用。
" <script src='file:///android_asset/jquery.min.js'></script>"
" <script src='file:///android_asset/jquery.lazyload.js'></script>"
2.添加 js方法調(diào)用
"<script type='text/javascript'>" +
"jQuery(document).ready(" +
"function(){" +
"$(\"img\").lazyload({" +
"placeholder : 'data:image/gif;base64,R0lGODlh/AF9AbMAAP///+7u7t3d3czMzLu7u6qqqpmZmYiIiHd3d2ZmZv4BAgAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgAKACwAAAAA/AF9AQAE/xDISau9OOvNu/9gKI5kaZ5oqq5s675wLM90bd94ru987//AoHBILBqPyKRyyWw6n9CodEqtWq/YrHbL7Xq/4LB4TC6bz+i0es1uu9/wuHxOr9vv+Lx+z+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WSGKwkXBqvBywEH0W0JKlFLLksNb8EBcbAGgTELAXPz8ckvDfMzi3QrV1wtHEoEQA7'," + /* 占位圖 */
"threshold : 50," + /* 距離圖片多少的位置處開始下載 */
"failure_limit : 10," + /* 最大不在加載范圍圖片數(shù), 主要是瀑布流布局時(shí)設(shè)置 */
"effect: \"fadeIn\"," + /* 圖片加載方式 */
"skip_invisible : true" +
"});" +
"});" +
"</script>" +
看方法的含義應(yīng)該是網(wǎng)頁框架加載完畢的時(shí)候再進(jìn)行的圖片的懶加載环础。placeholder代表的是占位圖剩拢,就是我放的是holder.gif的二進(jìn)制字符串,當(dāng)時(shí)以為時(shí)間緊還有文件也不大贯钩,直接就用的二進(jìn)制了办素。有想法的可以放本地加載引用試試。
3.替換 img標(biāo)簽的 src 屬性
因?yàn)閖query的懶加載框架的加載不是用普通的 src 屬性來加載的勺三,需要替換成data-original需曾,同時(shí)還要考慮 Video 跟 Audio 等標(biāo)簽里面的 src 屬性不能替換祈远,故寫了個(gè)匹配替換方法如下:
/**
* 變img標(biāo)簽里面的 src 屬性為 data-original
*/
public static String takeImgSrc(String htmlStr) {
String line=htmlStr;
String itemStr="";
String pattern = "<img.*?>";
// 創(chuàng)建 Pattern 對象
Pattern r = Pattern.compile(pattern);
// 現(xiàn)在創(chuàng)建 matcher 對象
Matcher m = r.matcher(line);
while (m.find()){
if (m.group(0)!=null){
if (m.group(0).contains("src")){
itemStr = m.group(0).replace("src","data-original");
line = line.replace(m.group(0), itemStr);
}
}
}
return line;
}
至此應(yīng)該可以實(shí)現(xiàn)仿微信的 lazyload 了绊含。不足的地方歡迎大家指正炊汹,共同進(jìn)步