In the previous post about jQuery we saw how this framework can be CPU consuming. In this post we’ll explore the programming model resulting from the jQuery API.
The jQuery API is simple to use:
- You first write a CSS selector. You get a set of DOM nodes matching this selector ;
- Then you apply functions to them (e.g. you attach them an event handler, or append an element) ;
- That’s all.
This way of programming is very concise and conciseness is generally good, so what’s wrong with that?
The first issue raised by this programming model is that, as every DOM elements are wrapped in a jQuery object, that’s not straightforward to use the native DOM API. Compare how the “Next” button is disabled with jQuery: and in Vanilla:
In this case, the Vanilla code is even more readable! (Ok, I must admit that the native DOM API sometimes sucks, using very long method names such as
document.findElementsByTagName, so not using it is not always a big frustration).
But did jQuery need to adopt this programming model? Why is it not possible to simply mix native DOM API with jQuery API, like in the following imaginary snippet?
As you see jQuery could have offered a better API with no viral nature, thus not requiring to reimplement the native DOM API…
If you look carefully at the snippet, you’ll see that almost every jQuery call could be replaced with a (modern) native DOM API call. The
$.find(element, selector) function could be replaced with
element.querySelector(selector) and the
$.click(element, callback) function could be replaced with
element.onclick = callback. That’s another remark about jQuery: it was very useful (not to say essential) several years ago, when the DOM API was very poor. But nowadays this API has evolved into a very more useable shape (and is still being improved) and the value added by jQuery is lower and lower. Actually, jQuery is just useful to ensure compatibility with old browsers.
Well, what did this post point out?
- The jQuery programming model is viral and forces you to choose between plain old DOM elements and the wrapping jQuery object ;
- Most of jQuery features are now already covered by the native DOM API ;
- Scattering selectors anywhere in the code is difficult to avoid, making this one very vulnerable to markup changes.