Search code examples
iosuicollectionviewwkwebview

Should I keep WKWebView in UICollectionView forever to avoid reloading?


I have some WKWebViews that load some HTML, and it takes a few seconds to load. I embed WKWebView in my UICollectionViewCell. So when the user scrolls the UICollectionView, the cell may be reused, but I don't want to load the HTML again when the user scrolls back.

Is it a good idea to keep the WKWebView forever even if they are off-screen? I don't want them to reload every time because that will affect user experience. However, I do worry about memory usage.

What is the best solution to tackle this issue? Thanks.


Solution

  • When reuse happens:

    • you should cancel the previous URL loading on the webView that is being reused; (1)
    • you should start loading of the new URL from scratch; (2)
      • load contents of URL over network (2.1)
      • load DOM into the web view (2.2)

    There are several ways to optimise this process:

    • avoid (1), i.e. avoid reuse - then your app gets into off-screen views and, most probably, will be killed due to memory pressure
    • try to avoid (2.1) - you can cache the data of URL before feeding it to the web view, and get the cached data when it's present. Or, alternatively, add a capability to send cache control headers on the server side, then WKWebView will do caching automatically.
    • try to optimise (2.2) - you can reuse the same WKProcessPool among all the webViews that you create, by assigning the same WKProcessPool instance to your WKWebViewConfiguration. WKWebView is the lightweight wrapper that proxies the input and output through the inter-process communication with the Web View Content Process. By reusing the process pool, you will achieve some level of reuse of the content processes that are created by each webView.