Corporate Blog


Extending HTML DOM – Facebook way explained


by , April 27, 2010, Javascript

When I started studying Facebook ML I’ve found a very interesting thing about HTML DOM which I didn’t know before. That’s how I can extend it with my own custom HTML tags just like I do it in .NET WPF/Silverlight for example.

That’s how we can do it:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Script-Type" content="text/javascript"/>
<title>Javascript Extension Example</title>

<script type='text/javascript'>
  var ExtML = {
    parseDocument: function(){
      document.documentElement.setAttribute('xmlns:extml', 'http://unique.domain.com/extml/2010/');

      for(tag in ExtML.DOM){
        if(typeof ExtML.DOM[tag] === 'function'){
          var extTags = document.getElementsByTagName('extml:' + tag);
          for(var i = 0; i < extTags.length; i++){
            ExtML.DOM[tag](extTags[i]);
          }
        }
      }
    }
  };

  ExtML.DOM = {
    youtube: function(element){
      var videoSource = element.getAttribute('video');
      element.innerHTML = '<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/' + videoSource + '&amp;hl=en_US&amp;fs=1&amp;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + videoSource + '&amp;hl=en_US&amp;fs=1&amp;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>'
    }
  };
</script>

</head>

<body onload='ExtML.parseDocument();'>
  <extml:youtube video="2yveywxVYsk"></extml:youtube>
  <extml:youtube video="8zHCucay3bc"></extml:youtube>
</body>
</html>

This is a very useful and powerful technique in some cases. For example, Html5media Project uses this trick to make available <video> and <audio> tags even when a browser doesn’t have native support for it.

Share
Add comment Share

Add Comment

Enter symbols from the box below to make us sure that you're not a robot: