预加载多个本地WebView

用户名

因为我只能找到一些过时的信息/无法解决我的问题,所以我决定再次提出这种问题。(请参阅过时/错误的解决方案:)


我的应用程序分为一个本机部分和一个HTML部分。HTML保存为本地文件(index.html),应加载到myWebView视图中。

@IBOutlet weak var myWebView: UIWebView!
func loadWebview() {
    let url = Bundle.main.url(forResource: "index", withExtension: "html")
    let request = URLRequest(url: url!)
    myWebView.loadRequest(request)
    myWebView.scrollView.isScrollEnabled = false
    myWebView.allowsLinkPreview = false
    myWebView.delegate = self
}

因为我的DOM树很大,所以从本机部分切换Web部件(单击按钮时)至少要花费很长的时间-至少是第一次切换-因为此后,我确定将缓存WebView请求

To my question从本地部件切换到Web部件时,如何应用程序初始化中预加载WebView以避免出现白屏(可能持续0.5s-1s)?

编辑:

WKWebView显示滚动条,而UIWebView不显示!

使用(类似于UIWebView)以下样式:

::-webkit-scrollbar {
     display: none;
}

无法正常工作并添加以下行:

webview.scrollView.showsHorizontalScrollIndicator = false
webview.scrollView.showsVerticalScrollIndicator = false

也根本不工作。

克里斯蒂克

首先,您应该切换到WKWebViewUIWebView 不再建议Apple使用。

其次,您可以创建一个网络视图池,这些视图将在应用启动时创建并要求加载。这样,当用户切换到Web界面时,Web视图可能已经有机会完全加载。

为此,您可以使用这样的类:

/// Keeps a cache of webviews and starts loading them the first time they are queried
class WebViewPreloader {
    var webviews = [URL: WKWebView]()


    /// Registers a web view for preloading. If an webview for that URL already
    /// exists, the web view reloads the request
    ///
    /// - Parameter url: the URL to preload
    func preload(url: URL) {
        webview(for: url).load(URLRequest(url: url))
    }

    /// Creates or returns an already cached webview for the given URL.
    /// If the webview doesn't exist, it gets created and asked to load the URL
    ///
    /// - Parameter url: the URL to prefecth
    /// - Returns: a new or existing web view
    func webview(for url: URL) -> WKWebView {
        if let cachedWebView = webviews[url] { return cachedWebView }

        let webview = WKWebView(frame: .zero)
        webview.load(URLRequest(url: url))
        webviews[url] = webview
        return webview
    }
}

并有时在应用启动时要求它预加载网址:

// extension added for convenience, as we'll use the index url in at least
// two places
extension Bundle {
    var indexURL: URL { return self.url(forResource: "index", withExtension: "html")! }
}

webviewPreloader.preload(url: Bundle.main.indexURL)

第三,您可能需要在控制器中使用容器视图而不是实际的Web视图:

@IBOutlet weak var webviewContainer: UIView!

剩下的就是在需要时将预加载的Web视图添加到容器中:

func loadWebview() {
    // retrieve the preloaded web view, add it to the container
    let webview = webviewPreloader.webview(for: Bundle.main.indexURL)
    webview.frame = webviewContainer.bounds
    webview.translatesAutoresizingMaskIntoConstraints = true
    webview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    webviewContainer.addSubview(webview)
}

最后,请注意,保持活动的Web视图实例可能会带来性能损失-内存和CPU方面的损失。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章