Reputation: 2227
I'm making my own Javascript library. It alters placeholders in inputs, which means adding support for < IE9 is pointless. Therefore I'm utilizing document.querySelectorAll
.
This is a stand-alone library, so I don't want to utilize other libraries such as Modernizr.js
Where should I test compatibility for that function and that an input actually supports placeholders?
http://jsfiddle.net/WR3Mr/1/ this is how I've done it so far (see the Javascript window and the comments I've left there). If doing like I've done now, on browsers that don't support these things it'll throw a ReferenceError on the user's script since PHR/PlaceholderRotator wouldn't be defined.
Is this the correct way to do it? Doesn't feel like it.
Upvotes: 0
Views: 498
Reputation: 328780
The standard way to do this is:
var foo;
if(document.querySelector) {
foo = document.querySelector;
} else {
foo = function() {
...code which emulates document.querySelector...
}
}
After that, you just call foo()
.
The main advantage to this approach is that you usually have an idea what you need to be done. So it makes sense to create a function for this which is specifically geared towards your needs. Then you can use this function in many places. If something is wrong, you need to fix it only on one (or two) places. Using the function switch above, you don't need expensive if()
constructs - just call the function; when you can, it's ready to serve.
Upvotes: 0
Reputation: 53246
You can check for querySelector()
support using:
if('querySelector' in document)
Or more simply:
if(document.querySelector)
You don't want to cause your script to perform extra work unnecessarily. If the pure function of the library is to act as a shim / shiv for placeholder
attributes, it'd be better to check whether these attributes are supported and handle them natively before running any more of your library.
Upvotes: 1