Difference between obtrusive and unobtrusive javascript
Asked Answered
T

6

55

What is the difference between obtrusive and unobtrusive javascript - in plain english. Brevity is appreciated. Short examples are also appreciated.

Tried answered 5/12, 2011 at 21:50 Comment(2)
possible duplicate of Why is using onClick() in HTML a bad practice?Ulrica
One ("obtrusive") is an old style (DOM 0) of applying behaviors to elements. The other ("unobtrusive") is a style promoted by John Resig (of jQuery fame). Both are acceptableWidespread
S
36

I don't endorse this anymore as it was valid in 2011 but perhaps not in 2018 and beyond.

Separation of concerns. Your HTML and CSS aren't tied into your JS code. Your JS code isn't inline to some HTML element. Your code doesn't have one big function (or non-function) for everything. You have short, succinct functions.

Modular. This happens when you correctly separate concerns. Eg, Your awesome canvas animation doesn't need to know how vectors work in order to draw a box.

Don't kill the experience if they don't have JavaScript installed, or aren't running the most recent browsers-- do what you can to gracefully degrade experience.

Don't build mountains of useless code when you only need to do something small. People endlessly complicate their code by re-selecting DOM elements, goofing up semantic HTML and tossing numbered IDs in there, and other strange things that happen because they don't understand the document model or some other bit of technology-- so they rely on "magic" abstraction layers that slow everything down to garbage-speed and bring in mountains of overhead.

Stultz answered 5/12, 2011 at 21:56 Comment(7)
"Don't build mountains of garbage"--Can you please give a small example or demonstration of this?Cootch
Is it about adding something like onkeypress="someFilter();" on each textfield individually, mixing into the HTML rather than using jQuery, and using multiple selectors and doing it all at once?Cootch
I don't endorse this anymore as it was valid in 2011 but perhaps not in 2018 and beyond.Stultz
@Stultz whats the significant changes happened in 2018, which makes obtrusive javascript valid?Mum
@Abdul a small example of mountains of garbage would make the garbage too small to make a single mountain.Quintan
@Stultz Doesn't obtrusive contradict HTML semantic? Would a programmer not want to keep JavaScript logic separated from HTML markup?Leto
@Mum Nothing... Only the trend changed. Basically everyone was advocating unobtrusive Javascript back in the days. Then React, Vue, etc. became popular and they use a syntax which is more similar to obtrusive Javascript. So it's a matter of preference, there are pros and cons for both the solutions.Grotto
F
39

No javascript in the markup is unobtrusive:

Obtrusive:

<div onclick="alert('obstrusive')">Information</div>

Unobtrusive:

<div id="informationHeader">Information</div>
window.informationHeader.addEventListener('click', (e) => alert('unobstrusive'))
Frascati answered 5/12, 2011 at 21:51 Comment(7)
This is solely from the programmer's point of view though: you could put everything in a separate JS script file and still have a site that is extremely obstrusive to users...Tuckerbag
@Tuckerbag StackOverflow is a website for programmers.Collettecolletti
@Collettecolletti - Yes, I know. My point is that the concept of "unobtrusive Javascript" is more about its impact on the user than its impact on the programmer. The user doesn't care whether there is JS mixed into the html, they just care whether the site works with their browser.Tuckerbag
@Tuckerbag So unobtrusive would be like: On a JS enabled page, I have text field filters, and a JS validation check onsubmit for the form. The submit button is hidden by default, make it display:block; using a JS action. On a JS disabled page, the button just never gets shown, thus disallowing the user from submitting a form non-validated from the front-end. Is this a correct example?Cootch
@Abdul - that is an example of obtrusive JS, because the page doesn't work without JS.Tuckerbag
@Tuckerbag - How would you validate a form from the front end then, without HTML5, in an unobstrusive way? Because if the page works without JS validation, then they can enter incorrect dataCootch
@Abdul - front end validation is a nice-to-have feature, but even when you have it you must always validate at the back end too to allow for malicious users who deliberately bypass your JS. The unobtrusive way is to have JS make the UI better (including validation if desired), but to still fall back to a traditional form submit with back-end validation when JS is turned off. That is, make sure the basic, essential functionality of your page works without JS, then apply JS to make it better/fancier - and most of your users will see the fancier version.Tuckerbag
S
36

I don't endorse this anymore as it was valid in 2011 but perhaps not in 2018 and beyond.

Separation of concerns. Your HTML and CSS aren't tied into your JS code. Your JS code isn't inline to some HTML element. Your code doesn't have one big function (or non-function) for everything. You have short, succinct functions.

Modular. This happens when you correctly separate concerns. Eg, Your awesome canvas animation doesn't need to know how vectors work in order to draw a box.

Don't kill the experience if they don't have JavaScript installed, or aren't running the most recent browsers-- do what you can to gracefully degrade experience.

Don't build mountains of useless code when you only need to do something small. People endlessly complicate their code by re-selecting DOM elements, goofing up semantic HTML and tossing numbered IDs in there, and other strange things that happen because they don't understand the document model or some other bit of technology-- so they rely on "magic" abstraction layers that slow everything down to garbage-speed and bring in mountains of overhead.

Stultz answered 5/12, 2011 at 21:56 Comment(7)
"Don't build mountains of garbage"--Can you please give a small example or demonstration of this?Cootch
Is it about adding something like onkeypress="someFilter();" on each textfield individually, mixing into the HTML rather than using jQuery, and using multiple selectors and doing it all at once?Cootch
I don't endorse this anymore as it was valid in 2011 but perhaps not in 2018 and beyond.Stultz
@Stultz whats the significant changes happened in 2018, which makes obtrusive javascript valid?Mum
@Abdul a small example of mountains of garbage would make the garbage too small to make a single mountain.Quintan
@Stultz Doesn't obtrusive contradict HTML semantic? Would a programmer not want to keep JavaScript logic separated from HTML markup?Leto
@Mum Nothing... Only the trend changed. Basically everyone was advocating unobtrusive Javascript back in the days. Then React, Vue, etc. became popular and they use a syntax which is more similar to obtrusive Javascript. So it's a matter of preference, there are pros and cons for both the solutions.Grotto
C
11
  1. Separation of HTML and JavaScript (define your JavaScript in external JavaScript files)
  2. Graceful degradation (important parts of the page still work with JavaScript disabled).

For a long-winded explanation, checkout the Wikipedia page on the subject.

Careful answered 5/12, 2011 at 21:52 Comment(5)
Pages can still gracefully degrade properly while using inline DOM 0 handlers.Widespread
@MattMcDonald: I'm not saying they can't? But then you break the principle of Separation of HTML and JavaScriptCareful
Your answer needs more clarity then.Widespread
You say important parts of the page...what about if it's a form and validation is required heavily. So unobtrusive would be like: On a JS enabled page, I have text field filters, and a JS validation check onsubmit for the form. The submit button is hidden by default, make it display:block; using a JS action. On a JS disabled page, the button just never gets shown, thus disallowing the user from submitting a form non-validated from the front-end. Is this a correct example?Cootch
@Abdul No, in an unobtrusive approach the user will still be able to submit the form without any js validation (if JS is disabled), so that the form is validated in the server. Bear in mind that client side validations are used for a better UX and there should always be a server side validation.Jennefer
P
3

To expand on Mike's answer: using UJS behavior is added "later".

<div id="info">Information</div>

... etc ...

// In an included JS file etc, jQueryish.
$(function() {
    $("#info").click(function() { alert("unobtrusive!"); }
});

UJS may also imply gentle degradation (my favorite kind), for example, another means to get to the #info click functionality, perhaps by providing an equivalent link. In other words, what happens if there's no JavaScript, or I'm using a screen reader, etc.

Prakrit answered 5/12, 2011 at 21:53 Comment(2)
I consider jQuery to be obtrusive to JavaScript. I would rather just see the events there in the static HTML, because they are going to be there just the same in the dynamically generated DOM.Satyr
@Satyr That doesn't have anything to do with jQuery specifically; UJS is framework-neutral.Prakrit
T
2

unobtrusive - "not obtrusive; inconspicuous, unassertive, or reticent."

obtrusive - "having or showing a disposition to obtrude, as by imposing oneself or one's opinions on others."

obtrude - "to thrust (something) forward or upon a person, especially without warrant or invitation"

So, speaking of imposing one's opinions, in my opinion the most important part of unobtrusive JavaScript is that from the user's point of view it doesn't get in the way. That is, the site will still work if JavaScript is turned off by browser settings. With or without JavaScript turned on the site will still be accessible to people using screen readers, a keyboard and no mouse, and other accessibility tools. Maybe (probably) the site won't be as "fancy" for such users, but it will still work.

If you think in term's of "progressive enhancement" your site's core functionality will work for everybody no matter how they access it. Then for users with JavaScript and CSS enabled (most users) you enhance it with more interactive elements.

The other key "unobtrusive" factor is "separation of concerns" - something programmers care about, not users, but it can help stop the JavaScript side of things from obtruding on the users' experience. From the programmer's point of view avoiding inline script does tend to make the markup a lot prettier and easier to maintain. It's generally a lot easier to debug script that isn't scattered across a bunch of inline event handlers.

Tuckerbag answered 5/12, 2011 at 23:39 Comment(0)
G
0

Even if you don't do ruby on rails, these first few paragraphs still offer a great explanation of the benefits of unobtrusive javascript.

Here's a summary:

  • Organisation: the bulk of your javascript code will be separate from your HTML and CSS, hence you know exactly where to find it
  • DRY/Efficiency: since javascript is stored outside of any particular page on your site, it's easy to reuse it in many pages. In other words, you don't have to copy/paste the same code into many different places (at least nowhere near as much as you would otherwise)
  • User Experience: since your code can is moved out into other files, those can be stored in the client side cache and only downloaded once (on the first page of your site), rather than needing to fetch javascript on every page load on your site
  • Ease of minimization, concatenation: since your javascript will not be scattered inside HTML, it will be very easy to make its file size smaller through tools that minimise and concatenate your javascript. Smaller javascript files means faster page loads.
    • Obfuscation: you may not care about this, but typically minifying and concatenating javascript will make it much more difficult to read, so if you didn't want people snooping through your javascript and figuring out what it does, and seeing the names of your functions and variables, that will help.
  • Serviceability: if you're using a framework, it will probably have established conventions around where to store javascript files, so if someone else works on your app, or if you work on someone else's, you'll be able to make educated guesses as to where certain javascript code is located
Gilroy answered 26/1, 2021 at 1:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.