When are JavaScript Blob objects garbage collected

2019-04-28 11:46发布

In modern browsers, it's possible to allocate a large object as a Blob, then request access to it via a URL. This URL will serve the stored object (such as an image's data) elsewhere in the browser.

How does the browser know when this URL is no longer needed, and the corresponding Blob data is free to be garbage collected?

1条回答
孤傲高冷的网名
2楼-- · 2019-04-28 12:30

The browser will eventually clear up this resource, however it may be some while (hours or days) before it is removed from memory/disk.

If you wish to explicitly remove the object, you may do so via revokeObjectURL.

var blob = new Blob([/*JPEG data*/], {type: "image/jpeg"}),
    url = (window.URL || window.webkitURL),
    objectUrl = url.createObjectURL(blob);

// use the object URL, eg:
var img = new Image();

img.onload = function()
{
    // release the object URL once the image has loaded
    url.revokeObjectURL(objectURL);
};

// trigger the image to load
image.src = objectURL;
查看更多
登录 后发表回答