Question

This question arose when I was working on answering another question about best practices for placeholder text in inputs and textareas.

Using the HTML5 placeholder is surely optimal, but at this point in time it still seems necessary to add a degraded solution for older browsers (using javascript).

JsFiddle here : http://jsfiddle.net/leifparker/DvqYU/16/

The question is : Since they both accomplish nearly precisely the same thing, why bother to include both? Why not just utilize the javascript-only solution, and forego the HTML5 implementation until it is (near) universally accepted?

Granted, with this specific example, adding the HTML5 placeholder attribute and the hasPlaceholderSupport() function is a fairly minimal addition of lines (4), but since the degraded support is desired, is there any reason to bother with the progressive redundancy?

I'm sure there is rationale on both sides, and I'm curious to hear it.

Thanks in advance!

Was it helpful?

Solution

There's a reason to bother. As time progresses, it's expected that all browsers will support the placeholder attribute. Right now, just a few browsers do not support it (most importantly, IE 9 and inferior, and the Android Browser). So, eventually, your placeholder fallback code will be unecessary. If you ship the website using the script for all browsers, in a few years, it will be completely unnecessary.

Instead, by using feature detection for falling back to a JavaScript solution only when necessary:

  1. You do not unnecessarily run a bit of JavaScript code in browsers which already support the placeholder attribute.
  2. You may only load the fallback script when necessary, saving a few bytes.

This is what libraries such as Modernizr and yepnope.js (included with Modernizr) already do. I'd recommend using Modernizr and extracting your placeholder polyfill to a placeholder-polyfill.js file, so your code could look like this:

Modernizr.load({
  test: Modernizr.placeholder,
  nope: 'placeholder-polyfill.js'
});

If you just want yepnope.js and run your own feature detection function(s):

yepnope({
  test: hasPlaceholderSupport(),
  nope: 'placeholder-polyfill.js'
});

This way, you save resource loading and improve performance for most browsers. In the future, all browsers would simply pass the test, improving performance. Then, you could simply remove the yepnope.js/Modernizr call.

For me, it's more of a mindset about future-proofing your code, while already taking advantage of modern browsers' capabilities.

OTHER TIPS

The gain I see is that you could only load jsFiddle when it was necessary. This saves the time needed load, parse, and execute extra code. Your page will load faster and the native html5 support is probably faster than emulating it in JavaScript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top