Working with HTML5 Blob Objects Was Made Easier

September 2, 2012

no comments

Working with HTML5 Blob Objects Was Made Easier

Lately, while getting ready for a HTML5 session, I found out that the File API specifications changed a little bit. In the past, in order to create a runtime Blob object you used the BlobBuilder object. That object is now deprecated and you should stop using it. Instead you are going to use the new blob object constructor which decrease the amount of code and objects you use.

Blob Object Constructor

The Blob constructor gets two parameters:

  • Array of data that will be appended to the blob.
  • Property bag that enable to configure the blob. You can use two properties: type and endings.
    The type property indicate the content type of the Blob. The endings property gets two values: transparent and native. Those values indicate how strings containing \n are written (in native they are written to match host OS file system conventions). The transparent value is the default.

Here is an example of using the new constructor:

var blob = new Blob(['alert("hello")'], {type: 'text/javascript'});

In this code example, a blob object is created and is holding some JavaScript code.

Full Example – Create a Runtime JavaScript Script Tag Using a Blob

Here is a simple example to create a JavaScript script tag and attach it to the document’s body using the Blob API:

<!DOCTYPE html>
    <meta charset="utf-8" />
    <script type="text/javascript">
        (function () {
            window.URL = window.URL || window.webkitURL;
            function contentLoaded() {
                var blob = new Blob(['alert("hello")'], { type: 'text/javascript' });
                var script = document.createElement('script');
                script.setAttribute('src', window.URL.createObjectURL(blob));
            window.addEventListener('DOMContentLoaded', contentLoaded, false);
        } ());
    <div id="container">

Running the code will produce an alert with the hello string.


The HTML5 specifications change from time to time and those changes can break your code. In this post, I wrote about a positive change in the specification regarding the use of blobs.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>