SoFunction
Updated on 2025-04-05

JavaScript implementation to obtain network communication progress

Network requests are an indispensable part of modern web development. Whether it is to obtain resources from the server or submit data, understanding the progress of the request is very important to improve the user experience. This article will explain in detail how to use the Fetch API and XMLHttpRequest (XHR) to perform network requests, and highlight how to obtain network request progress for both methods. In addition, how to get upload progress when using XHR for file uploading, as well as the limitations of the Fetch API will also be explored.

Fetch Basics

The Fetch API provides a powerful and flexible interface for operating network requests. It is a low-level API that controls all aspects of requests. The following is a basic Fetch API call example that acquires resources over the network.

fetch('/data')
  .then(response => {
    if() {
      return (); // Assuming the response is JSON
    }
    throw new Error('Network response was not ok.');
  })
  .then(data => (data))
  .catch(error => ('Fetch error:', error));

In the above code,fetchThe function call returns aPromise, when the response arrives and succeeds, enter.thenMethod processing, if there is an error,.catchProcessed in the process.

Get the Fetch request progress

Due to Fetch's returnResponseThe object does not directly expose the read progress of the original data stream. but,ResponseThe object'sbodyThe attribute is aReadableStream, can be used to read data streams.

To get the progress of the Fetch request, you can estimate the progress by reading the chunk size in the data stream.

fetch('/data')
  .then(response => {
    const contentLength = ('Content-Length');
    let receivedLength = 0; // received that many bytes at the moment
    let reader = ();
    let chunks = []; // array of received binary chunks (comprises the body)

    return new ReadableStream({
      start(controller) {
        function push() {
          // "done" is a Boolean and value a "Uint8Array"
          ().then(({done, value}) => {
            if (done) {
              ();
              return;
            }
            
            (value);
            receivedLength += ;
            
            (`Received ${receivedLength} of ${contentLength}`);
            
            // Enqueue the next data chunk into our target stream
            (value);
            push();
          });
        }
        
        push();
      }
    });
  })
  .then(stream => new Response(stream))
  .then(response => ())
  .then(blob => (blob)) // Do whatever with the blob
  .catch(error => ('Fetch error:', error));

In this example,ReadableStreamUsed to process the original data stream.().read()The data block is returned, and as the data block is received, the total amount of data that has been received can be calculated.receivedLengthand estimate progress.

XMLHttpRequest Basics

XMLHttpRequest is an old-fashioned technology, but is still widely used to perform network requests in browsers.

Here are the basic usages of XHR:

let xhr = new XMLHttpRequest();
('GET', '/data', true);

 = function() {
  if ( === 200) {
    let data = ();
    (data);
  } else {
    ('Request failed. Returned status of ' + );
  }
};

();

In the above code snippet, first create a new oneXMLHttpRequestobject, then pass.open()The method initializes a request. exist.onloadProcessing the response in the processing function and.onerrorerrors that may occur in the process.

Get XHR request progress

Unlike the Fetch API, XHR providesprogressEvents, can be used to track the progress of the request.

let xhr = new XMLHttpRequest();
('GET', '/data', true);

 = function(event) {
  if () {
    let percentComplete = ( / ) * 100;
    (`Progress: ${percentComplete}%`);
  }
};

 = function() {
  // The request is complete and data is available in ``
};

 = function() {
  ('Request failed');
};

();

In the above code,.onprogressThe event handler can get the current progress.is the number of bytes that have been downloaded, andis the total number of bytes (iflengthComputabletrue).

Use XHR to upload files and get progress

XHR can track the upload progress when uploading files. Here is an example of xhr uploading files and getting progress:

let file = ('fileupload').files[0]; // Assuming <input type="file" >
let xhr = new XMLHttpRequest();
let formData = new FormData();

('file', file);

 = function(event) {
  if () {
    let percentComplete = ( / ) * 100;
    (`Upload Progress: ${percentComplete}%`);
  }
};

 = function() {
  if ( === 200) {
    ('File successfully uploaded');
  } else {
    ('Upload failed. Returned status of ' + );
  }
};

 = function() {
  ('Upload failed.');
};

('POST', '/upload', true);
(formData);

In the above example,FormDataUsed to build a form data object.Object binding allowedprogressevents, thereby tracking the upload progress.

Why can't Fetch get upload progress

The Fetch API currently does not support monitoring of upload progress in the specification.fetch()The promise returned by the function will not be resolved until the request is completed, and no information on the intermediate state is provided. Since the design of the Fetch API tends to provide a set of streaming data processing methods, it does not directly provide support for state management in requests.

Developers can use Service Worker technology or Observables as an alternative to monitor upload progress to a certain extent, but these methods are relatively complex to implement and do not have the native advantages of XHR in this regard.

Summarize

Understanding and implementing monitoring of network request progress is crucial to creating a friendly user experience. By usingXMLHttpRequestofprogressEvents or utilizing the Fetch APIReadableStreamInterface, developers can provide users with real-time feedback, enhancing their confidence and satisfaction with the application. In addition, in the file upload scenario, due to the certain limitations of the Fetch API, XHR provides a more suitable choice to accurately obtain the upload progress. Although these technologies have their own advantages and disadvantages, choosing an appropriate method to monitor the progress of network requests can significantly improve the interactivity of web applications. In the future, with the development of web standards, Fetch API may add more complete functions to monitor transmission progress, but as of now, XHR is still the preferred tool for tracking progress.

This is the article about JavaScript realization to obtain network communication progress. For more related content on JavaScript to obtain network communication progress, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!