search
HomeJavajavaTutorialIntroduction to WebView loading optimization methods

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);

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);//网络不可用时只使用缓存 
}

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
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!