Course contentsShow
← Web Development
Lesson 2712 of 2,98248. File Uploads and HandlingFree lesson

Memory Management with Object URLs

Use URL.createObjectURL() as an alternative to data URLs for better memory efficiency with large images.

Memory Management with Object URLs

You'll learn how to use URL.createObjectURL() to preview files more efficiently than data URLs, especially when working with large images.

The Memory Problem with Data URLs

When you use FileReader.readAsDataURL() to preview an image, the entire file gets encoded into a base64 string and embedded directly in your HTML. For a 5MB photo, that becomes a ~7MB string stored in memory—and it stays there until the DOM element is removed and garbage-collected. With multiple large images, your page can become sluggish.

A Better Approach: Object URLs

URL.createObjectURL() creates a temporary reference (a special blob: URL) that points directly to the file data in memory, without copying or encoding it. Think of it like giving someone directions to your house versus photocopying your entire house and handing them the copies.

const fileInput = document.querySelector('#upload');
const preview = document.querySelector('#preview');

fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  
  // Create an object URL (much faster, less memory)
  const objectURL = URL.createObjectURL(file);
  
  preview.src = objectURL;
});

Cleaning Up

Unlike data URLs, object URLs must be manually released when you're done:

// When removing or replacing the preview
URL.revokeObjectURL(preview.src);
preview.src = ''; // Clear the image

// Or in a cleanup function
const cleanup = () => {
  URL.revokeObjectURL(objectURL);
};

This tells the browser to free the memory. Without revoking, the reference persists even after the image is removed from the DOM.

Key Takeaway: Use URL.createObjectURL() instead of data URLs for file previews—it's faster, uses less memory, but requires manual cleanup with URL.revokeObjectURL() when done.