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.scrollView addObserver:selfforKeyPath:@"contentSize"options:NSKeyValueObservingOptionNewcontext:nil];

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

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if ([keyPath isEqualToString:@"contentSize"]) {

        dispatch_async(dispatch_get_global_queue(0,0), ^{

            //document.documentElement.scrollHeight

            //document.body.offsetHeight

            [_webView evaluateJavaScript:@"document.documentElement.offsetHeight"completionHandler:^(id_Nullable result, NSError * _Nullable error) {

                CGRect frame =_webView.frame;

                frame.size.height = [result doubleValue] + 50;

                _webView.frame = frame;

                _scrollViewHeight =220 + _webView.height;

                _scrollView.contentSize =CGSizeMake(kScreenWidth,_scrollViewHeight);

            }];

        });

    }

}

第三步:移除观察者

- (void)dealloc

{

    [_webView.scrollView removeObserver:selfforKeyPath:@"contentSize"];

}

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

---------------------

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容