iOS webView以及WKWebView計算高度慢,加快載入速度等問題
我們開發詳情頁面,有的時候需要計算webView或者WKWebView的高度,然後再計算scrollView的高度,把webView放到scrollView上面。但是計算webView高度這個過程很耗費時間,原因是以下代理,網頁徹底載入完才會計算出來高度,我們需要的是先算出高度,先出現網頁的文字,至於網頁的圖片,可以慢慢快取顯示全。這樣不至於白屏時間過長。
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
/**計算高度*/
dispatch_async(dispatch_get_global_queue(
[_webView evaluateJavaScript:@"document.documentElement.offsetHeight" completionHandler:^(id_Nullable result, NSError *_Nullable error) {
//獲取webView高度
CGRect frame = _webView.frame;
frame.size.height = [result doubleValue] + 50;
_webView.frame = frame;
_scrollViewHeight = 220 + _webView.height;
_scrollView.contentSize = CGSizeMake(kScreenWidth, _scrollViewHeight);
}];
});
}
注:上邊的代理被樓主棄用,太耗費時間了。取而代之用下面的方法:(用的WKWebView舉例說明的) 第一步:新增觀察者[_webView.scrollViewaddObserver:selfforKeyPath:@"contentSize"options:NSKeyValueObservingOptionNew
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPathisEqualToString:@"contentSize"]) {
dispatch_async(dispatch_get_global_queue(0,0), ^{
//document.documentElement.scrollHeight
//document.body.offsetHeight
[_webViewevaluateJavaScript:@"document.documentElement.offsetHeight"completionHandler:^(id_Nullable result, NSError * _Nullable error) {
CGRect frame =_webView.frame;
frame.size.height = [resultdoubleValue] + 50;
_webView.frame = frame;
_scrollViewHeight =220 + _webView.height;
_scrollView.contentSize =CGSizeMake(kScreenWidth,_scrollViewHeight);
}];
});
}
}
第三步:移除觀察者
- (void)dealloc
{
[_webView.scrollViewremoveObserver:selfforKeyPath:@"contentSize"];
}
總結:以上這個方法,不能說特別快速載入,但是在我這裡速度至少提升了幾倍。我也在找更好的優化方法,比如快取等等。有知道的更好的方法的小夥伴,歡迎貼出來,樓主感激!!!