JavaScript onprogress Event: Monitoring Resource Loading

The onprogress event in JavaScript is a crucial tool for monitoring the progress of resource loading, whether it’s downloading a file, retrieving data from a server, or loading media content. This event is essential for providing feedback to users, allowing them to understand that a process is underway and how much has been completed. This guide will provide a comprehensive overview of the onprogress event, including its syntax, usage, and practical examples.

What is the onprogress Event?

The onprogress event is triggered periodically while a resource is being loaded. This event provides crucial information about the loading process, such as how much data has been transferred and how much is left to be downloaded. It’s particularly useful for enhancing user experience by displaying progress indicators. Key features of the onprogress event include:

  • Real-time Updates: The event fires repeatedly as the resource loads, allowing for dynamic updates of progress information.
  • Progress Tracking: Provides metrics like the total amount of data expected to be loaded and the amount of data already loaded.
  • User Feedback: Enables developers to display meaningful loading indicators, which helps reduce user frustration.

Purpose of the onprogress Event

The primary purpose of the onprogress event is to allow developers to track and visualize the progress of resource loading. This is important for several reasons:

  • Improved User Experience: By showing progress indicators, you keep the user informed and engaged.
  • Better Performance Monitoring: You can track network performance by analyzing progress events and loading speed.
  • Resource Optimization: Monitoring the progress helps optimize how resources are loaded and displayed.

Syntax of the onprogress Event

The onprogress event can be attached to various objects that support resource loading, such as XMLHttpRequest, fetch API responses, and media elements (<audio>, <video>).

Using addEventListener

The recommended way to handle the onprogress event is through the addEventListener method:

element.addEventListener('progress', function(event) {
  // event handling logic here
});
  • element: The HTML element or JavaScript object that triggers the progress event.
  • 'progress': The event name.
  • function(event): The callback function to be executed when the event occurs.
  • event: The event object containing information about the progress of the resource loading.

Using onprogress property

Alternatively, you can directly assign a function to the onprogress property of the element:

element.onprogress = function(event) {
  // event handling logic here
};

This method is straightforward but may not be suitable for scenarios requiring multiple event listeners.

Important Event Properties

The progress event object has several useful properties that provide information about the loading process:

Property Type Description
`lengthComputable` Boolean Indicates whether the total size of the resource is known. Returns `true` if the total size is available; otherwise, `false`.
`loaded` Number The amount of data currently loaded, in bytes.
`total` Number The total size of the resource being loaded, in bytes. This is only meaningful when `lengthComputable` is `true`.

Note: The total property is only available if the server provides a Content-Length header, which is not always present. Use lengthComputable to determine whether the total size is known. 💡

Practical Examples

Let’s delve into some practical examples to illustrate how the onprogress event can be used effectively in different scenarios.

Example 1: Tracking File Upload Progress with XMLHttpRequest

This example demonstrates how to use the onprogress event to track the progress of a file upload using XMLHttpRequest.

<input type="file" id="fileUploadProgress" />
<progress id="uploadProgress" value="0" max="100"></progress>
<div id="uploadStatus"></div>

<script>
  const fileInputProgress = document.getElementById('fileUploadProgress');
  const progressElement = document.getElementById('uploadProgress');
  const statusDiv = document.getElementById('uploadStatus');

  fileInputProgress.addEventListener('change', function() {
    const file = fileInputProgress.files[0];
    if (!file) {
      statusDiv.textContent = 'No file selected.';
      return;
    }

    const xhr_progress = new XMLHttpRequest();
    xhr_progress.open('POST', '/upload'); // Replace '/upload' with your server endpoint

    xhr_progress.upload.onprogress = function(event) {
      if (event.lengthComputable) {
        const percentage = (event.loaded / event.total) * 100;
        progressElement.value = percentage;
        statusDiv.textContent = `Upload progress: ${percentage.toFixed(2)}%`;
      } else {
        statusDiv.textContent = 'Unable to compute upload progress.';
      }
    };

    xhr_progress.onload = function() {
      if (xhr_progress.status === 200) {
          statusDiv.textContent = 'Upload completed successfully.';
      } else {
          statusDiv.textContent = `Upload failed with status: ${xhr_progress.status}`;
      }
    };

    xhr_progress.onerror = function() {
        statusDiv.textContent = 'Upload failed due to network error.';
    }

    const formData_progress = new FormData();
    formData_progress.append('file', file);
    xhr_progress.send(formData_progress);
  });
</script>

Output:

The HTML displays a file input, a progress bar, and a status message. When a file is selected, the JavaScript code initiates an upload. The onprogress event updates the progress bar and status message, providing live feedback on the upload progress. The final status of the upload is displayed on completion.

Note: The /upload URL should be replaced with a real server-side endpoint that is able to handle file uploads. ⚠️

Example 2: Monitoring Download Progress with Fetch API

This example demonstrates how to use the onprogress event with the Fetch API to monitor the download progress of a resource.

<button id="downloadButton">Download File</button>
<progress id="downloadProgress" value="0" max="100"></progress>
<div id="downloadStatus"></div>

<script>
  const downloadButton = document.getElementById('downloadButton');
  const downloadProgress = document.getElementById('downloadProgress');
  const downloadStatus = document.getElementById('downloadStatus');

  downloadButton.addEventListener('click', async function() {
    const response = await fetch('https://dummyimage.com/300x200/000/fff.jpg'); // Replace with actual URL
    if (!response.ok) {
      downloadStatus.textContent = 'Download failed.';
      return;
    }

    const reader = response.body.getReader();
    const contentLength = response.headers.get('content-length');
    let receivedLength = 0;

    const read = async () => {
      const { done, value } = await reader.read();
      if (done) {
          downloadStatus.textContent = 'Download completed successfully.';
          return;
      }

      receivedLength += value.length;
      if (contentLength) {
        const percentage = (receivedLength / contentLength) * 100;
        downloadProgress.value = percentage;
        downloadStatus.textContent = `Download progress: ${percentage.toFixed(2)}%`;
      } else {
        downloadStatus.textContent = `Downloaded ${receivedLength} bytes.`;
      }

      read();
    };

    read();
  });
</script>

Output:

The HTML includes a button to start the download, a progress bar to show the download progress, and a status message to provide feedback to the user. Clicking the button will begin downloading a sample image, and as the image is downloaded, the onprogress event will update the progress bar and display the percentage of completion on the status message.

Note: You will see the progress update when the content-length header is available in the response. 🧐

Example 3: Tracking Video Load Progress

This example shows how to use the onprogress event with an HTML5 video element to display the loading progress of the video.

<video id="videoProgress" controls width="320" height="240">
  <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>
<progress id="videoLoadingProgress" value="0" max="100"></progress>
<div id="videoStatus"></div>

<script>
    const videoElement = document.getElementById('videoProgress');
    const videoProgressElement = document.getElementById('videoLoadingProgress');
    const videoStatusElement = document.getElementById('videoStatus');

    videoElement.addEventListener('progress', function(event) {
        if (event.lengthComputable) {
            const percentage = (event.loaded / event.total) * 100;
            videoProgressElement.value = percentage;
            videoStatusElement.textContent = `Video loading: ${percentage.toFixed(2)}%`;
        } else {
            videoStatusElement.textContent = 'Unable to determine video loading progress.';
        }
    });

    videoElement.addEventListener('loadeddata', function() {
        videoStatusElement.textContent = 'Video ready to play.';
    });

    videoElement.addEventListener('error', function() {
      videoStatusElement.textContent = 'Error loading video.';
  });
</script>

Output:

The HTML includes a video element, a progress bar, and a status message. When the video is loading, the onprogress event updates the progress bar and status message with the loading percentage. When the video is loaded, it shows a message that the video is ready to play.

Note: Video loading progress is shown through the progress event, and loadeddata event is used to notify the user when the video is ready to be played. 🎵

Browser Support

The onprogress event is widely supported by all modern browsers, ensuring compatibility across different user environments.

Note: While broad support exists, always ensure your code includes proper error handling and falls back gracefully for older browsers or environments that might not support it. ✅

Conclusion

The onprogress event is an indispensable tool for web developers seeking to provide users with real-time updates on resource loading. By monitoring download or upload progress using the onprogress event, you can create more user-friendly, responsive, and engaging web applications. Whether you’re downloading files, uploading data, or loading media content, the onprogress event enables you to track loading progress and provide timely feedback to users, enhancing overall user experience.