WKWebview加载速度优化
$[timeformat('2021-10-08T10:50:29+08:00')]

高度计算问题优化

使用WKWebView进行性能调优 WebView性能、体验分析与优化--美团出品 iOS使用NSURLProtocol来Hook拦截WKWebview请求并回放的一种姿(ti)势(wei)

被放弃的方法

- (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];

第二步:观察者监听webView的contentSize变化

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPathisEqualToString:@"contentSize"]) {
        dispatch_async(dispatch_get_global_queue(0,0), ^{
           [_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"];
}