Android WebVIew caching mechanism to explain

Foreword

As the H5 with short development cycles, flexibility and good, so now Android App mostly embedded Android Webview components Hybrid Development

But I know you must be in trouble Android Webview performance issues, especially prominent are: slow loading & consumption flow

Today, I will address performance issues Android Webview put forward some effective solutions.

table of Contents

1.WebView performance issues

1.1 H5 slow page loads

1.1.1 rendering speed is slow

1.1.2 Resource page loads slowly

1.2-consuming traffic

2. WebView web caching

2.1 browser cache mechanism

2.2 Application Cache caching mechanism

2.3 Dom Storage caching mechanism

2.4 Database caching mechanism

2.5 IndexedDB caching mechanism 

2.6 File System

2.7 caching mechanism Summary

3 cache mode


1.WebView performance issues

1.1 H5 slow page loads

1.1.1 rendering speed is slow

H5 the front page rendering speed depends on two aspects:

Js resolution efficiency

Js resolution process itself is complex, analytical fast enough & the front page more involved JS code files, so add up can lead to very low resolution efficiency Js

Phone hardware performance

Because of the fragmentation of Android models, which results in the performance of mobile phone hardware devices can not be controlled, and most of the Android mobile phone hardware devices can not achieve very, very good hardware performance

Summary: The above-mentioned two reasons for the slow page rendering speed H5.

1.1.2 Resource page loads slowly

H5 page more generally, every load a page H5, will generate more network requests, HTML main URL own request, HTML external reference JS, CSS, font files, the picture is also a separate HTTP request.

Each request serial, string together so many requests, which leads H5 resource page loads slowly.

1.2-consuming traffic

Each time you use H5 page, users will need to reload Android WebView page of H5, H5 every load a page, will generate more network requests (mentioned above), each request serial, string together so many requests, this results in data usage will be more.

The above-mentioned problems led to the H5 Android WebView with Native Native pages experience a wide gap.

2. WebView web caching

Cache that off-line storage, which means that after loading the page H5 is stored in the cache area can also be accessed when there is no network connection

= Embedded WebView nature of H5 page in Android, so, Android WebView own caching mechanism is actually a caching mechanism H5 page

Android WebView addition to the new File System caching (caching mechanism H5 newly added page, the back will be a brief introduction) does not support, other support.

Android WebView own caching mechanism there are five:

  1. Browser cache mechanism
  2. Application Cache caching mechanism
  3. Dom Storage caching mechanism
  4. Web SQL Database caching mechanism
  5. Indexed Database caching mechanism

2.1 browser cache mechanism

The agreement in advance of the HTTP Cache-Control (or the Expires) and a Last-Modified (or an Etag) fields such mechanisms to control the file cache

The following details Cache-Control, Expires, Last-Modified & Etag four fields

Cache-Control: long files for controlling the local cache valid

The server returned packet: Cache-Control: max-age = 600, it indicates that the file should be cached locally, and when the effective length is 600 seconds (from the request). In the next 600 seconds, if there is a request to this resource, the browser will not issue an HTTP request, but direct use locally cached files.

Expires: Cache-Control same function, i.e., controlling the cache valid time

Expires HTTP1.0 is standard in the field, Cache-Control is standard HTTP1.1 newly added field

When these two fields appear at the same time, Cache-Control the higher priority

Last-Modified: identifies the file were last updated on the server

When the next request, if the file cache expires, the browser through the band-Modified-Since field the If this time, sent to the server, the server compares the time stamp to determine whether a file has changed. If there are no changes, the server returns a 304 tells the browser to continue using the cache; if there are changes, then return to 200, and returns the latest files.

Etag: Function with Last-Modified, namely identity documents were last updated on the server.

The difference is, Etag characteristic values ​​is one pair of strings that identifies a file.

When the query whether there are updates to the file server, the browser by the If-None-Match field to feature a string sent to the server, and file server to match the features of the latest string to determine whether the file updates: no update package back to 304 , an update package back to 200

Last-Modified Etag and can be used simultaneously according to the demand one or two. When the two simultaneously, as long as the group is one of the conditions is met, consider file is not updated.

Common usage is:

Cache-Control used with the Last-Modified;

Expires used with an Etag;

That is used to control a cache valid time, for after a cache miss, check with the service for updates

Feature

Pros: Support Http protocol layer

Inadequate: the need for the first time after loading the cache files will be generated; limited browser cache memory, the cache is likely to be cleared; cached files are not checked.

For solving the above problems, you can refer hands Q offline package

Scenarios

Store static resource files, such as `JS, CSS`, fonts, pictures and so on.

Android Webview records will be cached files and file content will exist in the current app's data directory.

Implementation

Browser cache mechanism is used by the browser kernel, usually to achieve a standard that Android WebView built automatically.

2.2  the Application Cache caching mechanism

Cache file units, and there is a certain file update mechanism (similar to the browser cache mechanism)

AppCache principle has two key points: manifest and manifest file attributes.

HTML referenced by the manifest file manifest attributes in the header

manifest file: The above is a file appcache ending, it is a common file that lists the files need to be cached

When the browser first loads an HTML file, parses the manifest attributes, and read the manifest file to obtain Section: a list of files to be cached under CACHE MANIFEST, and then the file cache

// principle as follows:

AppCache after the first load generation, but also update mechanism. Cached files if you want to update, you need to update manifest file

Because the browser loads the next time, in addition to using the default cache, it will also check the manifest file in the background, there is no modification (byte by byte)

Found to have modified, it will retrieve the manifest file of Section: CACHE MANIFEST list of files to check for updates at

check the manifest file and update the cache file also comply browser cache mechanism

Such as when the user manually clear the cache AppCache next loaded, the browser will regenerate the cache can also be regarded as a cache update

AppCache cache files, and browser cache files are stored separately, because there are AppCache 5MB (sub-HOST) in the local space constraints

Feature

Easy to build Web App caching, designed specifically for offline Web App developed for use caching mechanism, AppCache complements the browser cache mechanism.

Scenarios

Storing static files (such as JS, CSS, font files)

Implementation     

   // 通过设置WebView的settings来实现
        WebSettings settings = getSettings();
        String cacheDirPath = context.getFilesDir().getAbsolutePath()+"cache/";
        settings.setAppCachePath(cacheDirPath);
        // 1. 设置缓存路径
        settings.setAppCacheMaxSize(20*1024*1024);
        // 2. 设置缓存大小
        settings.setAppCacheEnabled(true);
        // 3. 开启Application Cache存储机制

Note that each Application is called only once WebSettings.setAppCachePath () and WebSettings.setAppCacheMaxSize ()

2.3  Dom Storage caching mechanism

Value to be provided - by the storage string Key

DOM Storage divided sessionStorage & localStorage; both use substantially the same, except that a different scope:

a.sessionStorage: have temporary, that is associated with the page of data is stored, it can not be used after the page is closed

b.localStorage: are persistent, i.e., the saved data can be used after the page is closed.

Feature

Storage space (5MB): storage space for different browsers, such as Cookies only 4KB

Storage safe and convenient: Dom Storage data stored in the local interaction, and does not require frequent server

Unlike Cookies every time the page request, the network will send a request to the server

Scenarios

Temporary storage, simple data

Instead you do not need to let the server know that information is stored in this traditional method of cookies

Dom Storage mechanism similar to the mechanism of Android SharedPreference

Implementation     

// 通过设置 `WebView`的`Settings`类实现
WebSettings settings = getSettings();
// 开启DOM storage
settings.setDomStorageEnabled(true);
        

2.4  Database caching mechanism

Based on the database storage mechanism `SQL`

Feature

Take advantage of the database, the data can easily add, delete, modify, query

Scenarios

Data storage structure for the database

Implementation      

  // 通过设置WebView的settings实现
        WebSettings settings = getSettings();
        String cacheDirPath = context.getFilesDir().getAbsolutePath()+"cache/";
        settings.setDatabasePath(cacheDirPath);
        // 设置缓存路径
        settings.setDatabaseEnabled(true);
        // 开启 数据库存储机制

According to the official explanation, Web SQL Database storage mechanism is no longer recommended (no maintenance), replaced by IndexedDB caching mechanism.

2.5  the IndexedDB caching mechanism 

NoSQL database belongs, the character string stored by Key - Value to be provided

Dom Storage storage mechanism similar to the key-value storage

Feature

Powerful, easy to use, data manipulation by transaction mechanism of the database, the object can generate an index of any familiar, easy access.

Storage space, the default 250MB, much larger than Dom Storage.

Flexible, Key-Value manner to access objects, can be made of any type of values ​​or objects, including the binary.

Asynchronous API calls to avoid waiting affecting experience.

Scenarios

Stores complex, structured data amount of data

Implementation

// achieved by setting the WebView settings, just set it to automatically open support JS IndexedDB storage mechanism, Android 4.4 began to join in support for IndexedDB, simply turn on the switch to allow JS to perform just fine.

  WebSettings settings = getSettings();
  settings.setJavaScriptEnabled(true);

 

2.6 File System

To provide a virtual file system data H5 page

Can create a file (folder), the read, write, delete, traversal operation, as Native App access the local file system as

The virtual file system is run in a sandbox

WebApp different virtual file system is isolated from each other, virtual file system and local file systems are also isolated from each other.

The virtual file system provides two types of memory: temporary & Persistence:

Temporary storage: automatically assigned by the browser, but the browser may be recycled

Persistent storage space: the need to explicitly apply; own management (browser does not recover, it will not clear the contents); storage space through quota management, an initial quota will apply for the first time, the quota exhausted need to apply again.

Feature

Large volume of data can be binary data storage, the resource file may be pre-loaded, you can directly edit the file.

Scenarios

Management data through the file system

Specific use

Since the File System is a caching mechanism H5 new entrants, it does not support Android WebView

2.7 caching mechanism Summary

3 cache mode

Cached Mode is a way to save the local cache when before that how to read the web page is loaded H5

Method used to perform

That tells Android WebView when read cache, the manner in which to read cache

Android WebView comes with cache mode there are four kinds:

// cache mode Description:

      // LOAD_CACHE_ONLY: do not use the network, only read the local cache data

      // LOAD_NO_CACHE: do not use the cache, only to get data from the network.

      // LOAD_DEFAULT: (default) to decide whether to fetch data from the network in accordance with cache-control.

      // LOAD_CACHE_ELSE_NETWORK, as long as there is local, whether expired or no-cache, use the data in the cache.

Specific use

WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

 

Published 57 original articles · won praise 26 · views 40000 +

Guess you like

Origin blog.csdn.net/Ever69/article/details/104479626