Home  >  Article  >  Web Front-end  >  无所不能的WebView(二) 在WebView中对html网页中的资源进行加速_html/css_WEB-ITnose

无所不能的WebView(二) 在WebView中对html网页中的资源进行加速_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-21 08:58:021813browse

最近有一个新需求,用手机流量的时候,webview加载页面的时候速度不是很快,能不能将静态文件缓存到sd卡呢,然后下次再访问这个网页的时候,把上次缓存的静态文件从sd卡拖拽过来,不走流量了,这样既省了流量,又让加载速度提升了。下面来写一个小测试吧(js放在在asseat里面)~

shouldInterceptRequest

在API11开始,shouldInterceptRequest被引入,可以解决这一类问题,这个方法可以通知app从本地加载指定的资源,而并非从网络中加载。

WebView请求回网络,返回响应的数据,再调用shouldInterceptRequest方法来替换webView自行加载网络数据的方法,使用app所提供本地数据。WebResourceResponse需要指定MIME类型,编码格式。

    webview.setWebViewClient(new WebViewClient() {       {        @Override        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {           return replaceJs(view, url);        }    });    protected WebResourceResponse replaceJs(WebView view, String url) {        if (url.startsWith("http://img1.cache.netease.com/f2e/lib/js/ne.js")) {            return new WebResourceResponse("text/html", "utf-8",                    FileTool.streamFromAsset(this, "js/hlct-com.js"));        } else {            return null;        }    }public class FileTool {    public static InputStream streamFromAsset(final Context ctx, final String file) {        try {            return ctx.getAssets().open(file);        } catch (Exception ignored) {        }        return null;    }}

通过以上的代码就可以对webview中的js资源替换掉了。但加快网页打开的同时会增加app的apk包的大小(资源都放在本地了),空间换时间(时间换空间)的选择就看你的了。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn