Read noscript tag content reliably in all browsers

The first step in our 4 part plan to solve the problem of responsive images using current browser standards is to reliably access the content inside a noscript tag. Modern browsers support access to the content of the noscript tag through either the innerHTML property or the textContent property. Since innerHTML is encoded, and is also read-only in IE<9, and textContent seems to contain markup perfectly in supported browser, it is the property we will polyfill.

The first job is to feature detect the property, which is done simply with this piece of code:

var div = document.createElement("div"); 
div.innerHTML = "<noscript><span></span></noscript>"; 
var elements = div.getElementsByTagName("noscript"); 
if (elements.length && elements[0].textContent) return; 

 
If we need to add the property, we have to resort to retreiving the markup of the page and parsing it with a regex. I know this may be frowned upon, but in this case it is quick and fairly reliable. In this case we also need to path the XmlHttpRequest object, and then retrieve the markup of the current browser location via ajax.

patchHttpRequest(); 
var xmlhttp = new XMLHttpRequest(); 
xmlhttp.onreadystatechange = function() { 
  if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { 
    var regex = /<script (.|\n)*?>(.|\n)*?</script>/igm; 
    var tags = document.getElementsByTagName("noscript"); 
..

 
Finally, we loop through each noscript tag, and set the textContent property.

var results = [], response = xmlhttp.responseText; 
var i=0, len=tags.length;
while (i < len && results) {
  results = regex.exec(response); 
  tags[i].textContent = results[1]; 
  i++; 
} 

 
Visit the github page to view the code packed together with some dom and ajax helper code.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s