Home Java javaTutorial Introduction to WebView loading optimization methods

Introduction to WebView loading optimization methods

Mar 22, 2019 am 10:53 AM
android java

This article brings you an introduction to the method of WebView loading optimization. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

WebView loading optimization

When the frequency of use of WebView becomes frequent, the optimization of all aspects of it becomes increasingly important. What you can know is that every time we load an H5 page, there will be a lot of requests. In addition to the request of the HTML main URL itself, the JS, CSS, font files, and images referenced externally by the HTML are all independent HTTP requests. Although the requests are concurrent, when the overall number of web pages reaches a certain level, plus The browser parsing and rendering time, and the overall loading time of the Web become very long. The more files requested at the same time, the more traffic will be consumed. Then the optimization of loading becomes very important. I have no other experience in this area. There are probably three aspects:
One is the issue of resource localization
First of all, it is clear that with the current Due to network conditions, the speed of obtaining resources from the server through the network is far slower than reading them locally. Talking about various optimization strategies actually ignores the fact that "requiring loading" is the biggest stumbling block to speed improvement. So our first idea is to localize some heavier resources such as js, css, pictures and even HTML itself. Every time these resources are loaded, they are read and loaded from the local area. They can be simply remembered as "save". ·Get·Update".
1. "Save" - ​​package the above heavyweight resources into apk files, and fetch them locally every time the corresponding files are loaded. You can also not package it, dynamically download and store it during the first load and at subsequent intervals, and store all resource files in the Android asset directory;
2. "Get" - Rewrite the WebResourceResponse of WebViewClient The shouldInterceptRequest(WebView view, WebResourceRequest request) method intercepts the corresponding request through a certain identification method (such as a regular expression), reads the corresponding resource from the local and returns it;
3. "Update" - Establish a Cache Control mechanism , control the updates of local resources regularly or in the form of API notifications to ensure that local resources are up to date and available.
The second one is the problem of caching
If you do not adopt or do not fully adopt the first resource localization idea, then your WebView cache must be turned on (although this idea is different from the first idea) There are overlaps).

WebSettings settings = webView.getSettings(); 
settings.setAppCacheEnabled(true); 
settings.setDatabaseEnabled(true); 
settings.setDomStorageEnabled(true);//开启DOM缓存 
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
Copy after login

When the network is normal, the default caching strategy is adopted, and the cache is loaded when the cache is available and has not expired. Otherwise, resources are obtained through the network to reduce the number of network requests for the page.
It’s worth mentioning here that when we often use WebView to display pages in apps, we don’t want the user to feel that he is visiting a web page. Because if there are too many web pages in our app, and we give users the feeling that they are visiting web pages, our app will lose its meaning. (I mean why don't users use the browser directly?)
So at this time, the issue of offline caching deserves our attention. We need to allow users to still operate our app when there is no Internet, instead of facing a page that is the same as the network error in the browser, even if the operations he can perform are very limited.
My idea here is that under the premise of turning on caching, WebView detects network changes when loading the page. If the user's network is suddenly disconnected when loading the page, we should change the caching strategy of WebView.

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); 
if(networkInfo.isAvailable()) { 
settings.setCacheMode(WebSettings.LOAD_DEFAULT);//网络正常时使用默认缓存策略 
} else { 
settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);//网络不可用时只使用缓存 
}
Copy after login

Since there is a cache, there must be cache control. Similar to this, we must also establish a cache control mechanism to clear or update the cache regularly or by accepting server notifications.
The third one is to delay loading and executing js
In WebView, the callback of onPageFinished() means the completion of page loading. However, this method will not be triggered until the JavScript script is executed. If the page we want to load uses JQuery, it will not be rendered until the DOM object has been processed and $(document).ready(function() {}) has been executed. and display the page. This is unacceptable, so we need to lazy load Js. Of course, this part is the work of the web front-end.

This article has ended here. For more exciting content, you can pay attention to the Java Tutorial Video column of the PHP Chinese website!

The above is the detailed content of Introduction to WebView loading optimization methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

Oppo Find X8 design looks like a cross between Apple iPhone 16 Pro and OnePlus Open in early images Oppo Find X8 design looks like a cross between Apple iPhone 16 Pro and OnePlus Open in early images Sep 28, 2024 am 06:04 AM

Historically, Oppo has refreshed its flagship 'Find X' series in late winter or early spring, save for the original Find X that it announced in June 2018. To that end, the Find X7 and Find X7 Ultra are barely more than six months old at this point. H

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Lenovo reveals new color option for the 2024 Legion Y700 gaming tablet Lenovo reveals new color option for the 2024 Legion Y700 gaming tablet Sep 29, 2024 am 06:05 AM

Lenovo is gearing up to launch the 2024 Legion Y700 on September 29 in China. This new Android gaming tablet will be going against the RedMagic Nova, and the company has already confirmed almost all the specs of the device. Now, hours before the full

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Samsung Galaxy Z Fold Special Edition revealed to land in late October as conflicting name emerges Samsung Galaxy Z Fold Special Edition revealed to land in late October as conflicting name emerges Oct 01, 2024 am 06:21 AM

The launch of Samsung's long-awaited 'Special Edition' foldable has taken another twist. In recent weeks, rumours about the so-called Galaxy Z Fold Special Edition went rather quiet. Instead, the focus has shifted to the Galaxy S25 series, including

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles