LearnWhat is Unobtrusive JavaScript and Why it’s Important?

Andrew Chalkley
writes on January 16, 2014

Unobtrusive JavaScript is a best practice methodology for attaching JavaScript to the front-end of a website. It’s an ideal to strive toward and something we should bear in mind whenever we’re adding JavaScript to a site.

It is the separation of behaviour from markup or structure. Just like the CSS gurus of old taught us there should be a separation of layout from markup, there should be a separation of behaviour from markup. That’s HTML for the content and structure of the document, CSS for the layout and style, and Unobtrusive JavaScript for behaviour and interactivity. Simple.

What?

It boils down to this: your site, and it’s content, should still be accessible when JavaScript is unavailable – the only way to guarantee this is by employing Unobtrusive JavaScript techniques.

Adding JavaScript to your site should be an additive process, bringing better experiences to those who have the capabilities of running your code, not a destructive one for those who for whatever reason have JavaScript disabled or blocked or not fully implemented. This is known as Progressive Enhancement.

How?

Let’s look at an example where you want to open a popup window for external links on your site.

The Downright Hackish Way

The first way is the downright hackish way &emdash; a technique that early on gave JavaScript a bad reputation &emdash; of hijacking the href attribute on all anchor elements on the site.

<a href="javascript:window.open('http://www.w3.org/wiki/The_principles_of_unobtrusive_JavaScript')">W3C Article</a> 

This poses a big problem if JavaScript is unavailable. The link won’t work! It’s not a very maintainable technique either, since changing your linking technique would require you to change every external link.

The Less Obtrusive Way

The less obtrusive way would be to add the JavaScript to the onclick handler for every link.

<a href="http://www.w3.org/wiki/The_principles_of_unobtrusive_JavaScript" onclick="window.open('http://www.w3.org/wiki/The_principles_of_unobtrusive_JavaScript');return false;">W3C Article</a> 

While this is still a maintenance nightmare, it does work if the browser’s JavaScript is disabled. Without JavaScript the user won’t follow the link in a new window, but will be able to follow the link through the default link behavior.

The Unobtrusive Way

Now to the best way, the unobtrusive way. We’ll add a class attribute to all links that are to open in a new window. This is just like how we’d add a class to style similar elements. However, in this case we’ll add a class to add behavior to similar elements. Let’s add a class of new_window to our links.

<a href="http://www.w3.org/wiki/The_principles_of_unobtrusive_JavaScript" class="new_window">W3C Article</a>

<a href="https://en.wikipedia.org/wiki/Unobtrusive_JavaScript" class="new_window">Wikipedia Article</a>

Now we have two links, both with the class new_window, but with no JavaScript. As a bonus we could style new_window links differently too, but that’s not what we’re doing right now, we’re adding behaviour.

Next, create a separate JavaScript file called app.js. Let’s use JavaScript to get all the elements with the class of new_window. We do this with the following code:

    var anchors = document.getElementsByClassName("new_window");

Now we have a variable anchors with all anchors on the document with the class of new_window. Now we can iterate over all the anchors and add a function to the onclick attribute.

for (var i=0; i < anchors.length; i++) {
    anchors[i].onclick = function() { };
};

We can also add a little bit of code to open the link in new window.

for (var i=0; i < anchors.length; i++) {
    anchors[i].onclick = function() {
        window.open(this.href);
        return false;
    };
};

We’re using this.href instead of typing out the URL string (like "http://www.w3.org/wiki/The_principles_of_unobtrusive_JavaScript") because now the same code is being used on multiple links. Since we’re binding a function to onclick we have the this object to play with. In the on click handler, the this object is the given anchor that the onclick function is bound to. So this.href is the href of the link that has been clicked.

Why?

There are a number of reasons why you’d want to use Unobtrusive JavaScript. From the how-to above you can see that maintenance and updating functionality is a lot easier. But the benefits of being unobtrusive aren’t purely selfish. It’s about the user.

When a user comes to your site you can’t guarantee the device, browser or connection they have to your site. For example, older browsers wouldn’t be able to execute the above code since they don’t support the getElementsByClassName method. This would stop the script from being executed. Still they will be able to go to the site and follow the link in spite of getting a JavaScript warning in the status bar of their browser. Ideally, to be truly unobtrusive, you’d write some more code to fall back on to with older browsers, or alternatively use something like jQuery.

In the case of connectivity, JavaScript files should be included at the bottom of the page, giving more weighting to the HTML document and stylesheets to be downloaded first. Say your user is connecting via a mobile device with flaky connectivity. The HTML and CSS may get downloaded before the connection disconnects and fails to download the JavaScript files. You don’t want this mobile user to have a poorer experience than they’re already having. Imagine someone accessing your site from work and their somewhat paranoid system administrators strip out all JavaScript tags through their proxy or disable JavaScript on all their computers. The user is totally out of control in this case and they shouldn’t be penalised by not having their experience hindered by your inability to provide content or functionality that would work in their scenario.

Finally there are cases where screen-readers for visually impaired users disable or don’t fully implement JavaScript, so it’s important to make your content accessible. An accessible site is also a search engine optimised site. Having your content there-and-then on your site, behind working links, will guarantee the even the least sophisticated search engine spiders will be able to index your site and it’s contents. An indexed site is a visited site.

Conclusion

The astute readers will have noticed that even the less selfish reasons will ultimately pay off in your favor. Being unobtrusive on your own, your employer’s, or your client’s projects will ultimately bring more users and paying customers to your site. It’s win-win.

In your next project, when adding interactive behavior, why not try to employ unobtrusive techniques to your JavaScript code?

You can check out the sample code on github or download the source files in a zip file.

9 Responses to “What is Unobtrusive JavaScript and Why it’s Important?”

  1. Michel Joanisse on February 7, 2018 at 7:50 am said:

    👍 Very well written article. Thanks. Unfortunately a concept a lot of developers still struggle to understand or put into practice.

  2. Is 2017 now and do you think Unobtrusive JavaScript is still needed ?
    Specially since now there is so much focus on front end technologies, which will not work if javascript it disabled.

  3. Patrick on April 13, 2016 at 6:08 pm said:

    There could be situations where your application is fully dependent upon JavaScript. For example, I work in the mapping profession, where interactive web maps rely on JavaScript. If someone has JavaScript disabled, the map won’t work. What are we supposed to do? Display a static map? This is what we are trying to get away from with interactive maps on the web.

  4. Yes, Abraham, you are right. It depends on the use case. No one has JS turned off these days, so that’s not the issue. It’s mostly for SEO purposes. For public-facing news, shopping, or informational sites where search engine indexability is vital to users being able to find your site, unobtrusive javascript is undoubtedly important. You want the content of your site to be fully crawlable, and links should have explicit URLs so that they can be spidered, as explained above.

    Related to unobstrusive JS are the interrelated concepts of “progressive enhancement” and “graceful degradation”. The article talks about the first thing: progressively enhancing an experience w/ JS. W/o JS, the site will still work, but it’ll just suck a bit more.

    For web applications, there may not be a need to do unobtrusive JS beyond the info pages (about, how to use, contact us). Web applications, by nature, contain personalized info, data, etc, and you don’t want Google crawling around in it. Plus Google can’t login or process forms, so there’s no point in it.

  5. I think it depends on the purpose of the website. An application like treehouse, for example, requires javascript. If js is turned off, the user should not anticipate a web app to be fully functional. I think unobtrusive js is a wise goal, but a less functional web app could degrade the quality for the majority of visitors, while catering to a very small group of visitors.

  6. Does it make website little slow to load???

    • Andrew Chalkley on January 27, 2014 at 3:04 am said:

      Not any more than obtrusive sites. In theory a well made unobtrusive site should be faster. But you should always include your JavaScript at the end of the page so if it doesn’t load everything else has had chance to.

  7. Thank you. Accessibility is required in our programming and this is a great resource.

  8. Wow no Comment

Leave a Reply

You must be logged in to post a comment.

Want to learn more about Javascript?

Learn how to use JavaScript to add interactivity to websites.

Learn more