JEDI - Javascript Embedded Data Islands

If you want to embed data islands in your HTML, here is an easy way to do it.

First lets create a script tag with a data attribute and put the javascript values inside it like this:

<script data>
mydata="myvalue";
</script>  

We can use any javascript data we want, like objects, arrays, nested elements, etc. so lets try a more complex example:

<script data>
bizcard={
  firstname:'Hacker',
  lastname :'Extraordinaire',
  age      : 30,
  sex      :'male',
  avatar   :'myavatar.jpg',
  email    :'h4xorz@mailinator.com',
  phones   :['555-1234','555-5678','555-9999'],
  address  :{
    line   :'123 Main Street',
    city   :'New York',
    state  :'NY',
    zipcode:'22222',
    country:'US'
  }
};
</script>

The advantage of this method is that anybody visiting our page will be able to get all that data without using scraping tools, just get the script elements with data attributes and done:

function getdataislands(){
  var scripts=document.querySelectorAll("script[data]");
  for(var i=0,n=scripts.length; i<n; i++){
    alert(scripts[i].text);
  }
}

That way extensions can be easily built to get different islands of data and use them at will for unimaginable purposes; one comes to mind as an easy way to share bizcards for example.

JEDI Templates

Templates can be easily built to seek and replace all HTML tags in a document with their respective values from a data island. Say we use a span tag with a data attribute or an image tag with a data source, we could easily populate their content from the island.

Lets see the HTML:

<h3><span data="bizcard.firstname"></span></h3>
<img id="avatar" data="bizcard.avatar">
Phone:  <span data="bizcard.phones[0]"></span>
Address:<span data="bizcard.address.line"></span>

Now the code:

function loaddata(){
  var fields=document.querySelectorAll("span[data]");
  for(var i=0,n=fields.length; i<n; i++){
    fields[i].innerHTML=eval(fields[i].getAttribute("data"));
  }
}

function loadimages(){
  var images=document.querySelectorAll("img[data]");
  for(var i=0,n=images.length; i<n; i++){
    images[i].src=eval(images[i].getAttribute("data"));
  }
}

Here is the result:

( / )




  • As you can see, it is extremely easy to use templates to take advantage of data islands in HTML today as all modern browsers understand script data islands.