Can you measure the time it takes to load a web pa

2019-07-17 06:24发布

问题:

There are lots of questions regarding the WebView in Android taking too long to load, however I'd like to be able to time exactly how long it takes to completely load, and then display the result.

Is this possible? I could start a timer but does the WebView have an HTML OnLoad style call once it has loaded?

The code I have is basic:

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.pageloadtest);

        webView = (WebView) findViewById(R.id.webView1);
        webView.loadUrl("http://www.airometricwireless.com");
}

This loads the page fine. I just need to time how long it takes.

回答1:

Probably not scientifically accurately, but I guess you could call

long a, b;

mWebView.setWebViewClient(new WebViewClient() {

    public void onPageStarted(WebView view, String url) {
        a = (new Date()).getTime;
    }

    public void onPageFinished(WebView view, String url) {
        b = (new Date()).getTime;
    }
});

Then b - a.

Hope it helps.

Best regards.



回答2:

To get page loading finish, use

webView.setWebViewClient(new WebViewClient() {

   public void onPageFinished(WebView view, String url) {
        // do your stuff here
    }
});


回答3:

You can use onPageFinished but as the docs say, "When onPageFinished() is called, the rendering picture may not be updated yet."

Also it's only meaningful for simple pages as it won't factor in IFRAMEs or dynamically-loaded content e.g. JavaScript that loads other JavaScript such as social media buttons, adverts, tracking scripts etc. And it's typically that stuff that causes pages to feel unperformant.

What people often mean when they say "it's slow to load" is "it takes a long time before I can interact with the page" which is very different from how long it takes to load the assets. For this you probably want to test when an onDOMReady-like event fires from JavaScript, or if not using that, when non-deferred JS actually initialises.

Essentially, as soon as you have any dynamic loading behaviours in the page, onPageFinished becomes meaningless, and you need to measure with JS.

As with any performance problem;

  1. measure the interaction to discover the bottlenecks
  2. try to fix a bottleneck & measure again
  3. repeat until performance is acceptable.