Android Webview selects to load local js, css and other resource files when loading external html
When using WebView to load web pages, some fixed resource files such as js jquery packages, css, images, and other resources will be relatively large, loading directly from the network will lead to slow page loading and consume a lot of traffic. Therefore, these files should be packed in assets in the same app.
To solve this problem, we need to use the shouldInterceptRequest (WebView view, String url) function provided by API 11 (HONEYCOMB) to load local resources. In API 21, this method is discarded. It is used to reload a new shouldInterceptRequest and replace the url with the request parameter.
For example, if an icon.png image is already placed in assets and an external html file is loaded, you need to take out the image in assets and load it without getting it from the network again. Of course, you can replace the image link with file: // android_asset/icon.png in html, but this html cannot be shared in android, ios, and WAP.
Implementation Code:
webView.setWebViewClient(new WebViewClient() { @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { WebResourceResponse response = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ response = super.shouldInterceptRequest(view,url); if (url.contains("icon.png")){ try { response = new WebResourceResponse("image/png","UTF-8",getAssets().open("icon.png")); } catch (IOException e) { e.printStackTrace(); } } }// return super.shouldInterceptRequest(view, url); return response; } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { WebResourceResponse response = null; response = super.shouldInterceptRequest(view, request); if (url.contains("icon.png")){ try { response = new WebResourceResponse("image/png","UTF-8",getAssets().open("icon.png")); } catch (IOException e) { e.printStackTrace(); } } return response; }}