skip to Main Content

This question is similar but not helpful.

To provide more feedback to users, we want to mimic the Waterfall column in the Network tab of Chrome, which deconstructs network requests into different stages and times them.

An example is included below.

In the particular, we want to indicate three stages:

  • Time uploading a file
  • Time processing a file on the server
  • Time download results

From the jQuery AJAX docs, it seems like beforeSend could be used to time file uploads. How about download time and time on server (TTFB in screenshot)?

Here’s how we implement AJAX calls:

async function doRequest() {
    // Set server URL.
    let serverUrl = 'https://test.com/test';

    // Set form data
    let imageFile = imageFile

    // Create request form.
    let formData = new FormData();
    formData.append('imageFile', imageFile);

    // Set request settings.
    let settings = {
        url: serverUrl,
        method: 'POST',
        timeout: 0,
        contentType: false,
        processData: false,
        data: formData,
        xhr: function() {
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
               if (xhr.readyState == 2) {
                    if (xhr.status == 200) {
                      xhr.responseType = 'blob';
                    } else {
                      xhr.responseType = 'text';
                    }
               }
            };
            return xhr;
        },
    };

    // Make request.
    try {
        let result = await $.ajax(settings);
        // Handle success
    } catch (error) {
        // Handle failure
    }
}

enter image description here

2

Answers


    1. For monitoring the upload state, I think you need XMLHttpRequestUpload and request.upload.addEventListener("progress", updateProgress) or request.onprogress and onloadend to check the loadend event. See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/upload.

    2. I don’t see there is a partucular HTTP state to determine the start of a response from a server. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Status. So from the HTTP API level (XMLHttpRequest) I dont think you can find a clue of that. But the browser should be able to know from TCP level. If checking devtools is not your preference, you may need to specify the timestamp in the response. Once the client gets the response, the client knows the start time of the response.

    3. The client can easily get the time that it receives the response from the server.

    So

    Dur_uploading = Time_loadend - Time_requeststarts

    Dur_serverprocessing = Time_responsespecified - Time_loadend

    Dur_download = Time_responsereceived - Time_resonsespecified

    Login or Signup to reply.
  1. Resource Loading and Timing

    As usual, someone had the same idea and has provided a pre-coded solution. I discovered these resources in an attempt to help you with this very complicated task. You can use the code as written or place it into a bookmarklet.

    I found a detailed article that describes how to use both the Navigation Timing API & the Resource Timing API The article I came across is titled (and found at):

    Assessing Loading Performance in Real Life with Navigation and Resource Timing

    The two prebuilt solutions provided by that article take completely different approaches to visualizing the data you seek.

    To use them without any effort, create a book mark for each of the following URLs:

    As mentioned, these are bookmarklets. They contain JavaScript code that can be executed directly on the page you have loaded. To use them,

    1. Load the page in Chrome that you want performance data
    2. Open you bookmarks and click on one of the two bookmarklets provided here

    The result will be the waterfall or other detailed data you are seeking.

    Note: The script can be blocked by content-security-policy and may not
    work on all sites.

    Source Code

    The waterfall chart like you originally asked about can be found at the following link. Note I am hosting this file for your answer. I can’t guarantee it will be available forever. Please download and host the file. (Open License)

    Waterfall by Andy Davies

    The more detailed version is found here: (MIT License)

    Performance-Bookmarklet by Michael Mrowetz.

    File Upload

    You’ll see the Resource Timing API provides this data. If you prefer to use the XHR API the a simple way to measure file upload time is by using xhr.upload object which takes an event listener for progress. As pointed out, this isn’t necessary given the previous tools.

    xhr.upload.addEventListener("progress", function(evt){
          // Initialize and finalize a timer here
          if (evt.lengthComputable) {
            console.log(evt.loaded + "/" + evt.total);
          }
        }, false);
    

    Server Processing Time

    In order to achieve the goal of measuring performance of the server and reporting it back to the client, the server must be involved in order to share its internal processing timing that you seek in your question. There is no way to determine that from the browser alone.

    I recommend the use of the Server-Timing feature with details about its use in the PerformanceServerTiming API

    It is fairly simple to use this API. As the example shows (using a NodeJS server), all your server has to do is respond with a specific HTTP header that contains the performance data you would like to display in the browser:

    const headers = {
        'Server-Timing': `
          cache;desc="Cache Read";dur=23.2,
          db;dur=53,
          app;dur=47.2
        `.replace(/n/g, '')
      };
    

    Using the information on the client is as simple as this (from the MDN link page):

    let entries = performance.getEntriesByType('resource');
    console.log(entries[0].serverTiming);
    // 0: PerformanceServerTiming {name: "cache", duration: 23.2, description: "Cache Read"}
    // 1: PerformanceServerTiming {name: "db", duration: 53, description: ""}
    // 2: PerformanceServerTiming {name: "app", duration: 47.2, description: ""}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search