I have a situation where an image is being set by the user either to a URL or with bytes that is converted into a blob object URL. My understanding is that in order to prevent resource leaks, I should be freeing the blob object URLs when they are changed, but I'm not sure if I'm checking the type of the old URL correctly. Currently, the way I'm doing it is to just check if the url starts with 'blob:'
. Here is a toy example function that demonstrates that it indeed seems to work:
var url;
for (i = 0; i < 5; i++) {
var oldurl = url;
console.log('i = ' + i)
if (i == 0 || i == 2 || i == 3) {
console.log('Switching to Object URL')
url = URL.createObjectURL(new Blob(new Uint8Array(0),
{type: 'image/png'}));
} else {
console.log('Switching to URL')
url = 'https://example.com/example-image.png';
}
if (oldurl && oldurl.startsWith('blob:')) {
console.log('Freeing old object url')
URL.revokeObjectURL(oldurl);
}
}
Is this the right way to do this? Is there a better way to do it?
I'll note that I've tried calling URL.revokeObjectURL
on strings that are not object URLs and it seems to work fine, so it's also not clear to me how much it matters that I correctly determine whether the URL needs to be freed.
Note: This is a TypeScript script, but I think the question is equally valid in Javascript, so I've tagged with both.
You are right, i think that currently there is no other way at all.