The magic of createObjectURL()

The web platform is maturing faster and faster, and we’re seeing the work normally done by native desktop applications now often shifting towards web-based applications instead. Features that may appear to have little importance can be really powerful when combined together.

A good example of this is URL.createObjectURL(). On it’s own, it really doesn’t do much. Paired with the HTML5 video and audio element, or even the good old image element, it gets to be really powerful.

URL.createObjectURL() is part of the URL-interface, which can be used to construct and parse URLs. URL.createObjectURL() specifically, can be used to create a reference to a File or a Blob. As opposed to a base64-encoded data URL, it doesn’t contain the actual data of the object – instead it holds a reference.

Let’s say you have a page that prompts the user to upload an image. The file input element is, as we all know, very simple and far from user friendly. When a user has selected an image, it would make sense (in a lot of cases) to show a preview of the image. We are now finally able to solve this problem in a simple and intuitive way:

Simple, right? This produces something like the following:

The nice thing about this is that it’s really fast. Previously, we’ve had to instantiate a FileReader instance and read the whole file as a base64 data URL, which takes time and a lot of memory. With createObjectURL(), the result is available straight away, allowing us to do things like reading image data to a canvas or the length of an audio file. Great, right?

One thing to keep in mind is that once you’re done with the generated object URL, you should revoke it. This frees up memory, which is usually handled automatically when you close the page or navigate away from it, but it’s generally a good idea anyway. Revoking the URL is a simple process – just call URL.revokeObjectURL(<objectUrl>) from the onLoad-handler of the element you are using it for.

Read more about createObjectUrl on the Mozilla Developer Network.

Read more from the Software engineering category
SUBSCRIBE TO OUR UPDATES
Menu