The rules of unobtrusive JavaScript

One of the most important things to keep in mind when writing JavaScript for the Web is to make it unobtrusive, since You cannot rely on JavaScript being available.

Sadly, there are many developers who do not seem to spend any energy at all on considering how to do that. Instead they choose to blindly forge ahead and assume that everybody who comes visiting will have full support for JavaScript and use a mouse.

Luckily there are a number of web developers who advocate unobtrusive JavaScript. One of the most noticeable ones is Chris Heilmann, who talks a lot about it in his book Beginning JavaScript with DOM Scripting and Ajax. Recently Chris held a workshop on the subject, and while preparing his materials for the workshop he defined The seven rules of Unobtrusive JavaScript:

  1. Do not make any assumptions: Don’t expect JavaScript to be available, and don’t expect the intended markup to be there.
  2. Find your hooks and relationships: Examine the HTML you are working with to find the best way of letting your script interact with it.
  3. Leave traversing to the experts: When possible, let CSS take care of finding the element you want to change.
  4. Understand browsers and users: Don’t deviate too far from the way browsers work and how users expect them to work.
  5. Understand Events: Learn how event handling helps you separate your JavaScript from your HTML.
  6. Play well with others: Make sure your script does not interfere with others, and make it hard for other scripts to interfere with yours.
  7. Work for the next developer: Make maintenance easier by writing logical code with clear variable and function names and commenting where necessary.

It’s all excellent advice that goes beyond unobtrusive scripting and into the realm of general best practices.

The JavaScript-focused blog Ajaxian asked Chris a few questions about unobtrusive JavaScript and links to his article in Unobtrusive JavaScript - Rules to work by. The comments on that post contain some examples of the careless attitude among many developers that I mentioned earlier. It’s fascinating to see people actively argue against unobtrusive JavaScript.

I guess no matter which part of web development you look at there will always be people who couldn’t care less about craftsmanship and quality, and are always on the lookout for shortcuts and ways to shut out minorities.

Posted on November 27, 2007 in Accessibility, JavaScript

Comments

  1. Wow, I only had time to read the first few comments, but it seems that some developers can be incredibly selfish. What excuse is, “target audience is lame (if on a browser that doesn’t support js they are either on a REALLY old machine or are paranoid types, either way they probably won’t spend any money on your product)”?!

    How do we attempt to convince that sort of developer?

  2. Great post, I really appreciate the tips. I found it startling while reading to realize that most Web Developers don’t use unobtrusive javascript. I take it a step farther on the AskApache.com sites javascript, and I couldn’t be happier with the results.

    It’s tough to get to the point where its second nature and you wouldn’t dream of doing it any other way. One thing that helped me understand the big picture was learning that javascript should be added AFTER you already have a semantically stable XHTML site utilizing CSS. Then you add the javascript.

  3. November 27, 2007 by Matthew Pettitt

    Unobtrusiveness is almost a side effect of good system design: thinking about the content of the site, tailoring the appearance to the content, then tailoring extra means of accessing the content to the site.

    If the whole system hasn’t been designed up front, though, it tends to get muddled in with the core functionality of the system, meaning that making it behave unobtrusively is almost impossible.

    AskApache is right with the good approach: stable (X)HTML + CSS site, then add client side scripting, if required, and if it produces a notable benefit to the user.

  4. November 27, 2007 by lyhana8

    Since i read some of your post about unobstrusive JS, I was looking for some ressources here they are :)

    thanks

  5. In terms of web programming I am a beliver that start with your XHTML add your CSS. If you need to use Javascript then add it right at the end this way you do not have to reverse engineer your site.

    A good idea is to get Firefox’s Web Developer toolbar nad use the Disable Javascript option whilst developing your site.

    I think Javascript should only be used for backend systems where you cant get away from it like AJAX, this way you can make it a requirement for your customer. But having it as a requirement for your actual end user is a bad idea and will reduce your viewing public.

    The same thing can be said about Flash.

  6. November 27, 2007 by Fabrice

    One thing that really bugs me with accessibility is that 99% of developers who don’t have easy means for testing the accessibility of their pages; have to work hard at it, while nobody ever says anything about improving the assistive software in the first place! By the looks of some examples of accessibility, the software that reads the pages could really use some improvement.

  7. All those excuses not to use unobtrusive JS remind me of the old excuses for not using CSS - “it’s to hard”, “it puts cost up”, “screw the user we know better” etc…

  8. And for those of you wanting to use unobtrusive JS to do Flash thingz, check this out: SWFOBJECT.

    A colleague of mine in the Netherlands (Ron Jonk) won a Dutch Accessibility award for the new Rabobank website, showing that corporate sites can be fully functional also when gracefully degrading. JS is used to present the site in Optima Forma, whilest every step “down” the JS ladder delivers a fully functional website, maybe looking a little less nice.

  9. I saw something very much like this on Digg recently, about table layout.

    There are a lot of condescending comments like “yes, but in the REAL world we have time constraints, and tables are just faster and work more coherently across browsers”. I see the same argument used here but against unobtrusive JS instead. Basically, it’s about the developer wanting a shortcut - engineers using substandard building materials because they don’t think the client will notice. This is definitely a problem and I think these guys will continue to pollute our business for years to come :(

  10. Held at Paris Web 2007, which I helped to organize, this workshop was really good, and you have to see how Chris teaches how works the event propagation… http://tinyurl.com/2enhhs

  11. November 27, 2007 by Stevie D

    One thing that really bugs me with accessibility is that 99% of developers who don’t have easy means for testing the accessibility of their pages; have to work hard at it, while nobody ever says anything about improving the assistive software in the first place!

    If the developers are using Firefox or Opera (which they should be!), it’s pretty easy to test a lot of accessibility features. In Opera, it takes one click/key to turn off images, one click/key to turn off stylesheets, and one context menu selection to turn off Java or Javascript. Then put your mouse to one side and navigate by headings, links and list-of-links, and you’ll have a pretty good idea how accessible your website is. (Yes, I know there is more to it than that, but that gives you a very good starting point)

  12. November 27, 2007 by Maniquí

    Don’t forget the Hijax concept!

  13. “Instead they choose to blindly forge ahead and assume that everybody who comes visiting will have full support for JavaScript and use a mouse.”

    You make these people sound so purposefully evil. I’d call them pragmatic. When you build anything, you need to make assumptions and you have to be practical.

    I assume you have a computer, your browser can parse HTML and CSS, and you have javascript turned on. That covers most people. I don’t hate/despise the people that don’t have a system that meets the minimum requirements but I also have to be realistic. Time and money are factors.

    Perhaps I should start making pages that assume nothing and will send you a copy of the webpage in the mail if you don’t have a computer.

    I’d like to know why the web is so pressured to be uniformly accessible? Other programs like games/OS/applications can have minimum system requirements - why can’t webpages?

  14. Written by Brian:

    I assume you have a computer, your browser can parse HTML and CSS, and you have javascript turned on.

    That’s some kind of false assumption. Say, I do have a computer, and my browser can parse HTML and CSS, but javascript is mostly turned off. It is not so often needed at all, really.

  15. As web developers, we are trying to improve the situation of incompatibility. I use Linux at home which means most of the popular games can’t be run natively because they don’t meet the “minimum requirements” (i.e. Windows). Why would you want to impose limitations like this in the web design world when it’s not really any harder to do for a competent developer? The argument that doing things right takes more time and money is ridiculous.

  16. Now I know why I don’t use JS very much (opting to try just about everything I can server-side with PHP). I have rule one down pat. That’s where my knowledge of JS drops right off I’m afraid.

  17. @Brian, well this assumes that web sites are pieces of software. They are only under the hood. In reality they are services or media content. With your argument it would be fine if a TV station were to expect a widescreen LCD for you to see the news. They don’t, as they want to offer the content to as many people as possible and rely on the technology to convert the signal as needed.

    This is exactly what we are doing with unobtrusive JavaScript - we offer the extras only to those that can digest them.

  18. November 28, 2007 by Anders Ytterström

    The last six months I have started to play with DOM scripting to make my sites interact. I must say that there isn’t a big deal really to implement it right: place the event handlers with javascript is a dozen extra lines maximum in the JS file.

    When making a HTTP request with javascript, I have a variable on the server side script I call isAjax which decides what to do when the script is finished. If isAjax is true, the result is printed, If not, the user is redirected in traditional manner.

    It’s all about finding the right guides. In my case, It was Jeremy Keith, Robert Nyman and Roger.

    Today, it’s a charm to be new to DOM scripting. Everything hard is already solved; it’s just about choosing well when it comes to teachers.

  19. November 28, 2007 by Dave Brimlow

    “opting to try just about everything I can server-side with PHP.”

    I try using a combination of css and php to replace jscript. I KNOW the security functions/procedures I can build into php.

    The whole argument about “most people have jscript on” is simply too similar to the old argument about IE a few years ago, “Why worry about my site not working in Mozilla or Opera … most people use IE anyway so who cares about a few techie geeks?”.

    Since FF and Safari (Mac’s resurgence) that attitude now costs them @ 30% of their visitors!

    Our firm relies on our website for business … I can’t stand the thought of losing even 1% of our visitors (potential customers) just because I was too lazy to cover all contingencies.

    Dave

  20. The engineers that continue to rely on shortcuts and sub-par development practices are the same folks that create these environments where a client wants everything yesterday. By polluting the web design/web development infrastructure with those nice shiny turds they call “Web 2.0 Applications,” these so-called “developers” (and yes, I use the term loosely) are nurturing a practice we see daily with most manufactured goods: build it quick and crappy so that folks will buy more goods.

    In my business I see more frequent requests for skipping over certain key steps in the initial phases of a project. I recently had one client who boldly asked me to “skip all those wireframe and prototype phases…I just want to see my web site in-action first and then I will decide whether I like it,” which to me is akin to saying “build my house first with no blueprints and then I will let you know what to change with the floor plans.” If any of the readers here have ever experienced this situation before can I get a big “ick?” :-(

    My point here is that these same quick-and-dirty approaches to web development are subordinate to a much larger issue: client expectations. People want things too fast for their own good. We are always going to have charlatans in our business who are out to make a quick buck and who place no manner of pride in their work. It is up to us to simply keep repeating to our clients that “you cannot rely on JavaScript, period.” Just my 2px…

  21. I am currently working with a team that is refactoring a mature FOSS CMS for accessibility. A good part of that work has been removing javascript and we are finding the same barriers to change as some of those reflected here.

    Web apps that rely on js for functionality are just not being developed for the real world. Call it unobtrusive javascript, or progressive enhancement, it all comes down to the same thing - functionality must not rely on scripts that may or may not be available. To do so cuts out potential users of those apps or websites.

    I believe point #1 is the most important. Some developers assume that browser sniffing is the way to go. They are then making the assumption that they only have to consider the user’s browser. Increasingly, javascript is being blocked by corporate firewalls so the workstation that has a js-enabled browser is still not going to receive javascript.

    Assumptions are dangerous things. And that includes the assumption that best practises which enhance usability and accessibility by all are simply related to accessibility for people with disabilities.

  22. This is one of the best articles on this subject that I’ve read. It sums it up nicely for people who don’t get it or don’t have time to read much in order to get it. I’m going to send this to a few people who haven’t listened to me on this subject yet! Thanks for writing it.

  23. Why not use JS to do, not graceful degrading, but upgrading instead?

    On the site http://laurasamulionyte.ten.lt (that I made for a friend) I use JS on the “graphic design” subpage. But I use it to do two things: first, to hide the text links under the thumbnails, and secondly to do the ‘onclick’ magic. This way, if you have JS, you don’t get to see the links, but without it you get the links to click anyway.

  24. I can see both sides of the arguments here. As an accessibility consultant I would always say don’t assume that JavaScript will be available, but as someone who has been using computers for a long time I also agree that we do have to make some assumptions. Take screen size for example. It isn’t safe to assume that everyone using your website will have a 1024x768 or greater size display, but where do we draw the line. Looking at statistics the vast majority of PCs (and I include Macs in this as they are personal computers too!) are using resolutions of 800x600 or greater. But then of course that ignores all the other devices like mobile phones and PDAs that can be somewhat smaller resolutions. Even coding only with HTML and CSS and no table layouts, there are limits to what can be displayed on a small mobile phone.

    JavaScript has been around for a long time now and is supported by many different browsers including screen reader software and mobile phone browsers. If we just had a blanket rule which everyone followed regarding JavaScript then it is unlikely that things would progress, for example we may not have got anywhere with making Ajax accessible. In other words, we have to be careful not to be so draconian that we stifle innovation, even though it may not be accessible to all.

    To take a real world example (not that I don’t think computing is real world though), if the escalator didn’t already exist it is unlikely that it would be invented now because it wouldn’t be accessible to many people, and yet what a loss that would be to the many who can use and benefit from an escalator.

    Richard Morton http://www.qm-consulting.co.uk/

  25. One other point which may be slightly veering off topic but I think is relevant. With so much image substitution going on in JavaScript now it is obviously important to make that degrade gracefully in the case of JavaScript not being available. I have however tested a number of examples where JavaScript is available but images are not and the results do not degrade gracefully because information is contained within the images and isn’t (or can’t) be supplemented by alt attributes because of the way the image substitution works. Needless to say this would fail the first priority one accessibility checkpoint, but I can see that it would be difficult for developers to anticipate.

    Any thoughts on this? Am I creating too artificial a testing situation here?

    Richard Morton

    [http://www.qm-consulting.co.uk/ “Accessible Web Design, Build, Test and Consultancy”]

  26. I recently read an interesting book that stressed the point that it is too easy to spend a lot of your time making only a small number of people happy, and I think that applies here: yes, we can make things pleasantly degrade, so that people with cellphones and screen readers can comfortably visit our sites, but is it really worth spending all of your time for that small part of the population, when you could be spending that time for a much greater part? I think rather than spending a lot of time worrying about the few people that won’t have good Javascript - or worse, are too paranoid to accept cookies - we should make the most of these technologies for the most people; to make the experience as interesting and engaging as it can be for the most people. Cell phones and screen readers will catch up, because there they have their own majorities to provide their own best experiences to by doing so.

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.