# Weak network experience optimization

When users use Mini Programs, they may fall into some scenarios where the network is not smooth, and some functions that rely strictly on the network may not be available at this time.

# Frame optimization

In order to make the Mini Program use more smoothly in the case of weak networks, the Mini Program framework has made the following optimizations to solve the experience of using Mini Programs on weak networks:

  1. Startup Mini Program supports asynchronous launch

The process that was started previously was synchronized Launch, when synchronizing in a weak network will appear when the page is stuck in Loading Page, Mini Program framework in the weak network when the default use of asynchronous launch To optimize the experience of the weak network startup Mini Program:

  • synchronization Launch: pull a new configuration, if there is a new code package will pull a new code package, and then start a Mini Program
  • asynchronous Launch: Use the default local cache configuration, code package to launch the Mini Program
  1. Support for weak networks/Offline one-time authorization

for wx.getLocation Need users To grant authorization Because the authorization relationship will be recorded in the background, but in the weak network or off the network when the request is difficult to pass, so the Mini Program framework in the weak network/Support one-time authorization to go through the process when the network is off:

  • When invoking the authorization class interface, flicks the authorization box directly to the local authorization, regardless of previous authorization.
  • In Weak Net/Use the result of this authorization during the period of network disconnection
  • After the network recovery, clear the one-time authorization results, and go back to the background to send a request to check the authorization logic.

In addition, Mini programs provide Cache manager To help developers solve the Mini Program weak network problems.

Currently, the following network-dependent functions can be improved by accessing the cache manager:

  • Features of Pure Display Class
  • Rely only on some user-authorized features

# Cache manager

Mini Programs provide a non-intrusive cache manager that developers can access without modifying the original business code. The cache manager has the following capabilities:

  • Cache regular network requests while the network is openUse a cache return for the network request when the network is weak.
  • When the network is open, for some wx api Call to cacheIn a weak network. wx api Is returned using the cache.

In simple terms, a cache manager can help developers quickly access cache capabilities without modifying the main logic of the Mini Program. The access process requires only a few extra lines of code:

// Create a cache manager
const CacheManager = wx.createCacheManager({
  origin: 'https://weixin.qq.com ', 
})

// Add Request Rules
cacheManager.addRules([
  '/cgi/home',
  '/cgi/detail/:id',
])

// Listen to the rules. wx.request Request, which is called by default when a weak network wx.request It will trigger
cacheManager.on('request', possibly  => {
  return new Promise((resolve, reject) => {
    // Matches whether there is a cache
    const matchRes = cacheManager.match(possibly )

    if (matchRes && matchRes.data) {
      // Using Cache Returns
      resolve(matchRes.data)
    } else {
      // No match for cache
      reject({errMsg: `catch not found: ${evt.url} `})
    }
  })
})

The above example uses wx.createCacheManager You can create a cache manager. There is only one instance of the cache manager in the world, and once it is successfully created, it means that the access is successful.

Developers need to add request rules that match which requests need to be cached, and requests that are not in the request rules are automatically passed. Once the request hits the rule, the result is cached when the network is clear, and the request is intercepted when the network is weak, and then triggered. request Event to the developer. The developer can decide in the event callback whether to use a cache return or not. If a cache return is used, no more network requests will be madeIf you still want to attempt to initiate a network request, you can do so as follows:

cacheManager.on('request', async possibly  => {
  try {
    // Still Go Network Request
    const res = await evt.request()
    
    // ......
  } catch (err) {
    // ......
  }
})

In order to accommodate more request scenarios, request rules support a variety of writing, such as:

cacheManager.addRule('/abc' ) // uri String, will automatically use the call wx.createCacheManager When the incoming origin Splicing, and then matching
cacheManager.addRule('GET /abc' ) // in uri String basis, the matching of the supplementary request method
cacheManager.addRule('/abc/:id') // With variable portion uri string

cacheManager.addRule(//(abc|cba)$/ig) // regular expression

cacheManager.addRule({
  method: 'POST',
  url: '/abc', 
  dataSchema:  [
    {name: 'param1',  schema: {value: /(aaa|bbb)/ig}}, 
    {name: 'param2',  schema: {value: '123'}},
  ],
}) // Rule object

More rules can be read. addRule file

For every request that hits a rule, a cache is generated according to a policy Id, if the cache generated by the two requests id The latter overrides the former, so you need to be aware of this when writing your rules. In general, requests url Different or the request method is different, the resulting cache id Must be differentIf the request parameters are different, you need to consider whether the hit rules take into account the parameters, the detailed cache id Generating strategy can refer to addRule file

The cache store uses separate user space (does not occupy the user's Storage), but there are limits on the number and size of caches, so don't use them unsparingly. Make good use of the rules to cache only necessary requests when possible.

Details on the use of the cache manager can be found in the api fileAlso available here[A fully operational example](https://github.com/WeChat mini-program /miniprogram-offline-demo ), Reference Examples of README Operation can be experienced.

# Cloud Hosting Usage CacheManager

adopt wx.cloud.callContainer The invoked interface can also be used wx.createCacheManager Optimize the weak network experience. The cache request requires the developer to call the addRule Adding rules. Here for addRule In the parameter url There is a uniform standard for fields: https://wx.cloud.callContainer/env/Service name /path , which env / Service name / path Corresponding wx.cloud.callContainer The identity field of the calling service. For example, for the following cloud calls, you can add caching rules as an example:

const res = await wx.cloud.callContainer({
    config: {
      env: 'test-123'
    },
    path: '/api/count',
    header: {
      'X-WX-SERVICE': 'express-server',
      'content-type': 'application/json'
    },
    method: 'GET',
    data: {
      action: 'inc'
    },
})

// Adding Cache Rules
cacheManager.addRule({
    url: 'https://wx.cloud.callContainer/test-123/express-server/api/count',
    method: 'get'
})

# Other

part wx api Caches are also performed after access to the cache manager. The list can be found wx.createCacheManager Documentation, developers can also adjust on their own which wx api Cache required.

It should be noted that, as wx.loginwx.checkSession Such interface support cache is not equivalent to the interface in the weak network is available, the cache is only the result of the last successful call to return, the logic of the interface itself will not change, that is, the cache return such as Code Such time-limited content will not be refreshed and will still be invalid. The cache here is provided only to reduce the cost of retrofitting some scenarios.

Other parts of the interface that require user authorization/Components will be supported on the weak web at the base library level, and the usage will be the same as before, and developers will not need to change it.