H5应用打开优化

最近上了一个重度依赖H5的应用。自测过程中发现首屏打开有白屏,一闪而过。
我怀疑是H5的实现有问题,所以我自己弄了一个简单的H5页面。


<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Modals and Keyboard Trapstitle>
    <meta name="description" content="Fixing tabindex">
    <meta name="viewport" content="width=device-width, initial-scale=1">
head>
<style type="text/css" media="screen">
body{margin: 0px;}
style>
<body style="background-color: #1E2831;">
body>
html>

我自测了几下,还是概率性出现问题。打开chrome的调试模式,发现是这样的:

H5应用打开优化_第1张图片
H5应用打开优化_第2张图片

DOMContentLoaded EventFirst Paint 两个事件触发的时机有先后,DOMContentLoaded提前完成的话。
那么我原生那边就撤掉了加载页面,但是还没有Paint,这时候页面是白色的。

大概在50ms之内,页面执行了paint,然后webview就有颜色了,表现的结果就是闪了一下。

我是这样改的:

public class YeshenWebView extends WebView {
	
	private final PageFinishHandle mPageFinishHandle = new PageFinishHandle();

	public void init(){

        setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mPageFinishHandle.onPageFinished(url);
            }
        });

	}

	@Override
    public void invalidate() {
        super.invalidate();
        mPageFinishHandle.invalidate();
    }

    // refer to:https://stackoverflow.com/a/14678910
    // When the onPageFinished called,the page not fully finish loading.
    // So the page flashing from white to gray...
    // To fix this bug, skip onPageFinished's callback when getContentHeight()==0
    private class PageFinishHandle {

        private boolean mWaitingCallback = false;
        private String mUrl = "";

        private boolean isReady() {
            return getContentHeight() > 0;
        }

        @UiThread
        private void invalidate() {
            if (!mWaitingCallback) return;
            if (isReady()) {
                mDelegate.onPageFinished(WebViewEx.this, mUrl);
                mWaitingCallback = false;
                mUrl = "";
            }
        }

        @UiThread
        private void onPageFinished(String url) {
            if (isReady()) {
                mDelegate.onPageFinished(WebViewEx.this, url);
                mWaitingCallback = false;
            } else {
                mWaitingCallback = true;
                mUrl = url;
            }
        }

    }
}

你可能感兴趣的:(Android,webview)