我们开发详情页面,有的时候需要计算webView或者WKWebView的高度,然后再计算scrollView的高度,把webView放到scrollView上面。但是计算webView高度这个过程很耗费时间,原因是以下代理,网页彻底加载完才会计算出来高度,我们需要的是先算出高度,先出现网页的文字,至于网页的图片,可以慢慢缓存显示全。这样不至于白屏时间过长。
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
/**计算高度*/
dispatch_async(dispatch_get_global_queue(0,0), ^{
[_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);
}];
});
}
[_webView.scrollViewaddObserver:selfforKeyPath:@"contentSize"options:NSKeyValueObservingOptionNewcontext:nil];
- (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"];
}
总结:以上这个方法,不能说特别快速加载,但是在我这里速度至少提升了几倍。我也在找更好的优化方法,比如缓存等等。有知道的更好的方法的小伙伴,欢迎贴出来,楼主感激!!!