Course contentsShow
← JavaScript
Lesson 2370 of 2,72348. Working with Binary DataFree lesson

Revoking Object URLs

Clean up memory by revoking object URLs with URL.revokeObjectURL() when they're no longer needed.

Revoking Object URLs

You'll learn how to free up memory by cleaning up object URLs when they're no longer needed.

Why Revoke Object URLs?

When you create an object URL with URL.createObjectURL(), the browser keeps that Blob or File in memory for as long as the URL exists. Even if you remove the reference from your page, the browser doesn't automatically know you're done with it. Think of it like borrowing a library book—you need to explicitly return it when you're finished, or it stays checked out forever (until you close the tab or browser window).

Using URL.revokeObjectURL()

The URL.revokeObjectURL() method tells the browser: "I'm done with this URL, release the memory." It takes the object URL string as its only argument:

const blob = new Blob(['Hello'], { type: 'text/plain' });
const url = URL.createObjectURL(blob);

// Use the URL (e.g., set it as an image src or download link)
const img = document.createElement('img');
img.src = url;

// Once loaded or no longer needed, revoke it
img.onload = () => {
  URL.revokeObjectURL(url);
  console.log('Object URL revoked');
};

After revoking, the URL becomes invalid and can't be used anymore. Trying to access it will fail.

When to Revoke

Revoke object URLs:

  • After an image/video has loaded
  • After a download link has been clicked
  • When removing elements that use the URL
  • Before creating new URLs in loops or repeated operations

Memory Management

Failing to revoke object URLs in long-running applications (like SPAs) can cause memory leaks. Each unreleased URL keeps its Blob in memory indefinitely.

Key Takeaway: Always call URL.revokeObjectURL() when you're done with an object URL to prevent memory leaks and free up resources.