iOS webView以及WKWebView计算高度慢,加快加载速度等问题

我们开发详情页面,有的时候需要计算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);

        }];

    });

}


注:上边的代理被楼主弃用,太耗费时间了。取而代之用下面的方法:(用的WKWebView举例说明的)

第一步:添加观察者

[_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), ^{

            //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"];

}


总结:以上这个方法,不能说特别快速加载,但是在我这里速度至少提升了几倍。我也在找更好的优化方法,比如缓存等等。有知道的更好的方法的小伙伴,欢迎贴出来,楼主感激!!!



猜你喜欢

转载自blog.csdn.net/zhaotao0617/article/details/53079777