Tactics to speed up WKWebView rendering of loadHTM

2019-03-13 08:19发布

I've been experimenting with stacking WKWebViews in a UINavigationController as a method of making a hybrid app that's more native than PhoneGap. It broadly works - I hook into decidePolicyForNavigationAction when a WKWebView hits a link, and push a new ViewController with the link it wants.

But the page loading is slow. I've done everything I can think of to speed it up - it's using loadHTMLString rather than a request to ensure everything is local - I've even tried stripping out the CSS and JS to see if that speeds it up, but no dice. It still takes at least 500ms for a short, HTML only, locally stored page to appear in the empty WKWebView. I can tell from debugging that the delay is not in reading the HTML from disk, but the time between loadHTMLString() and didFinishNavigation().

Does anyone have any tactics for fixing this? I'd try to preload the view, only I don't know which link the user is going to tap so I don't know what to preload.

3条回答
三岁会撩人
2楼-- · 2019-03-13 08:47

My way is to go less native and more web. 1. Work out a single page app, like http://m.ftchinese.com/phone.html 2. Bundle every resources (JS, CSS, Graphics as Base64) into one file. 3. Save that file to my Xcode project and use that file to launch the app, setting the baseURL as http://m.ftchinese.com/phone.html

The code here:

let templatepath = NSBundle.mainBundle().pathForResource("index", ofType: "html")!
let base = NSURL(string: "http://m.ftchinese.com")
var s = NSString(contentsOfFile:templatepath, encoding:NSUTF8StringEncoding, error:nil)!
self.webView!.loadHTMLString(s, baseURL:base)

This has some benefits: 1. I've already worked on the web app for many years so it's very stable. 2. The same approach can be used on Android, Windows Phone and Blackberry. 3. SPA has No paging loading. It feels very smooth.

查看更多
Root(大扎)
3楼-- · 2019-03-13 08:51

An interim answer - I am having some success creating the next view in advance, then using evaluateJavaScript to run document.body.innerHTML = "content" - it does not have the half-second delay. Of course, it means creating a WKWebview earlier than I would otherwise, but hopefully that isn't a performance killer.

查看更多
Rolldiameter
4楼-- · 2019-03-13 09:00

Update:

Both WKWebView and UIWebView delays on first run. It is more visible when using WKWebView. I have implemented class which warmups web views to resolve this issue. You can find Swift version of this solution here: https://github.com/bernikowich/WebViewWarmuper

Original answer:

Looks like WKWebView/UIWebView delays on first run. I've created simple class for boosting loading speed of web view with warming up. You can try sample project: https://github.com/bernikowich/NSTViewWarmuper

查看更多
登录 后发表回答