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.

Read noscript tag content reliably in all browsers

Responsive Images – what’s the problem?

Something I’ve been grappling with for a while is a good solid approach to loading the correct image at the correct screen size in a responsive design. This is hard one lots of people have been working on. Mainly because using an image tag means unrequired images are loaded before you have a change to change the src attribute, and there isn’t a semantic alternative available to the img tag (yet).

So what we need is a clean easy to use approach, that is semantic and can be progressively enhanced, is responsive, and that works across all browsers on all types of devices. Here’s the approach I will be following in the next few posts:

1. Consistently detect the contents of noscript tag
2. Append an appropriate img tag to the markup for script-enabled browsers
3. Change the image based on a call to matchMedia and the resulting MediaQueryList
4. Bonus: add support for Google’s webP format

Responsive Images – what’s the problem?