Why It's Time to Sunset jQuery
professionalaspnet.com
professionalaspnet.com
Think of it this way - Everyone loves Ruby on Rails. But Rails IS slow. But that doesn't mean I should re-write my code in just plain C, just because it is fast and Rails is no longer needed according to a bunch of bloggers.
I think this argument is not about Jquery and is about frameworks in general.
In my humble opinion, I think [1]
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
is better than: function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
[1]http://www.tizag.com/ajaxTutorial/ajax-javascript.phpI think you’re being too dismissive. It’s a fair question to ask, and the answer is not obvious and probably not the same for everyone on every project.
Frameworks like jQuery became popular for good reasons, including easy DOM manipulation, AJAX, and event management, and in particular for offering these tools within a single, widely tested, cross-browser API.
However, using native APIs instead is easier than it was a few years ago, unless you really still need to support very old browsers, and we’ve learned to use polyfill/shim strategies to fill in most gaps when we need to. We’ve also learned a lot about how to write better plain JS in that time, for which the folks developing popular JS libraries like jQuery deserve a lot of the credit. In effect, the major reasons for using jQuery have all become less important. Almost no-one really needs to write code like your “bad” example today, and even if they do, it’s the sort of thing you only do once and wrap up in your own library so you can reuse exactly the ideas you need and optimise it using the same tools as any other JS you write.
On the other hand, jQuery has a number of potential disadvantages. There are run-time performance questions that can only be answered by profiling, but they are fair to ask. In any case, fetching jQuery means more download bandwidth and more HTTP round-trips, which is definitely a real problem for performance, particularly with mobile networks. The obvious counter is to say everyone should load jQuery from a CDN like Google’s, but now you have a third-party dependency that is a potential risk to reliability, security and privacy, and in any case not all web sites/apps run on the public Internet, so that choice won’t be for everyone.
The thing that is increasingly bugging me is the universal dependency problem. Most of the little JS libraries I’ve looked at recently, things that do one simple job well, seem to depend on jQuery even if it offers no real advantage at all. jQuery has become the God Object of client-side JS development, and having one of those is rarely a good sign.
So while I certainly wouldn’t go as far as to say that jQuery is no longer useful, I don’t think we should take it for granted that using jQuery should somehow be the default choice.
If you're going to do that, it'd be good to open source it so other people can take advantage of it. Maybe abstract out some other cross browser stuff as well. Also, it would cool if it made the DOM api nicer to work with.
$(document).ready(function() {
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
})
});
Without jQuery: var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function() {if (this.readyState === 4) {
window.document.body.className += " done";
}};
oReq.open("GET", "test.html", true);
oReq.send();
Screenshots (blue indicates successful ajax):without jQuery: http://browsershots.org/http://evening-harbor-8654.herokuapp...
with jQuery: http://browsershots.org/http://evening-harbor-8654.herokuapp...
And good luck using your new ajax function :)
It will take time though as many people aren't even familiar with the native APIs.
$.get('test.html', function(r) {
window.document.body.className += " done";
});
But: This is not about short code. It's about readability. What's readyState 4? Why "open" a request before sending it? url: "test.html",
is clearly not equivalent to var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
so your example reeks of hyperbole.The first piece of code is GET'ing an arbitrary, presumably static webpage and injecting the word "done" into the body, while the second piece of code appears to be pulling data from a form, sending it to another webpage, and then displaying its response into a specific div.
As for the try/catch statements, I think the OP's point is that we don't need to worry about XMLHttpRequest failing anymore. The decision to support IE6 is up to you, but I think most web developers are willing to draw the line these days.
$.ajax({
url: 'ajax-example.php',
data: $('#myForm').serialize(),
success: function(data) {
$('#ajaxDiv').html(data);
}
});An interesting side note here is that the Rails analogy remains somewhat apt, in that much of the execution time in web applications is spent in the data store.
1. IE7 and above support the native XMLHttpRequest object; the code example is code is probably much longer than it needs to be (it can be trivially reduced by %50).
2. There is nothing to stop you from creating your own API. I had to do this because jQuery didn't interact well with a custom ASP.NET framework[1]
Here is how I do Ajax stuff using a small library that I wrote[2]:
var xhr = new $xhr(SOME_URL, function (data) { /* do stuff */ })
xhr.post(document.getElementById('form_id'));
[1] http://stackoverflow.com/questions/7810022/ajax-via-jquery-a...- If you use the standard jQuery hosted off Google's CDN, most users won't have to load it in the first place. So that overhead doesn't count. Only if you do some boneheaded thing like rolling your own version and hosting it on your server are you going to guarantee every visitor has to download jQuery.
- Parsing jQuery is trivial for most modern browsers. If your web app has performance issues, it's not jQuery's fault, it's your fault.
- querySelectorAll is not a replacement for jQuery. If you think it is you haven't been making good use of jQuery.
This article seems like a post by someone who didn't even know how to do basic things against the DOM, finally learned how to do them and now thinks there's no use for jQuery. It's absurd.
jQuery still has plenty of uses. I'm not saying you have to use it, or are making a mistake if you don't, but the assertion that it should be abandoned is ludicrous.
Ugh.
Well, it depends. [1]
[1]: http://www.stevesouders.com/blog/2013/03/18/http-archive-jqu...
Also at this point the base jQuery UI is pretty solid, but plugins are a different matter.
Been there, done that. And it's a pain in the *
You'll find yourself needing a method to add or remove classes eficiently. So you'll rewrite .addClass() and .removeClass()
Then you'll need a clean way to make Ajax and callbacks. You'll rewrite .ajax() and .when()
Then you'll need to fade something in all browser. So you'll rewrite .animate()
Ad lib.
JQuery Minified and GZipped is 35k (not 90 as the op said, ignoring the gziping.) JQuery is cached in most browsers. The performance hit is not worth the pain of re-inventing the wheel.
The problem is not JQuery, it's bad code. Bad code won't magically disappear in vanilla JS.
You don't need to rewrite it, cf. this shim [1] for example.
> Then you'll need a clean way to make Ajax and callbacks. You'll rewrite .ajax() and .when()
They are plenty of good Ajax implementations, for example this one [2]. If you need promises, there are good libraries too [3].
> Then you'll need to fade something in all browser. So you'll rewrite .animate()
Applying a fading effect on an element shouldn't be a mandatory feature. You can just use CSS3.
[1] https://developer.mozilla.org/en-US/docs/DOM/element.classLi...
Or, you'll use element.classList.add()
>You'll rewrite .ajax() and .when()
XHR isn't really too verbose.
>So you'll rewrite .animate()
Or you'll do elem.style.transition = ... and use elem.addEventListener;
Really, the plain DOM isn't that bad. If you make one or two sugar methods, they'll be far, far, far smaller than jQuery, and probably far faster.
What's the point to use shims or polyfills if it means including some others libraries ?
JQuery is not slow. If you .addClass() two hundred divs, sure. But for basic DOM manipulations, it's fine.
JQuery is not heavy. 32kb. It may be in cache. You'll likely gain that twice 32kb by optimizing your png.
This anti-JQuery war is a silly fad started by people who don't make websites.
And as per arguments like "a fadein should not be mandatory blablabla", explain it to the client. It may work. Or it may not.
Every time I have to look at plain ol' javascript it feels like my eyes are going to bleed. Regardless of whether I wrote it myself or whether another developer wrote it.
On the other hand, jQuery (still not the Miss World of programming languages..) is far easier on the eyes.
Also, for most apps, the performance impact isn't all that noticeable since most of the performance hit happens due to reflows and not because of jQuery. Plus, the Google CDN jQuery is pretty well cached in most browsers.
var list = querySelectorAll(selector);
var i;
for (i = 0; i < list.length; i++)
list[i].value = value;
Is just as readable as: $(selector).val(value);
Except that the jQuery example requires you to be familiar with jQuery. The first, however, just requires you to be familiar with a for loop, which is a common construct in many languages. Being faster is just a happy by-product.I, personally, am starting to use Dart instead, because it is a nice middleground between jQuery and raw DOM manipulation; it doesn't hide the details like jQuery does and it's still fast.
Ihe best argument I can see is with XMLHttpRequest, which is still a pain because it doesn't have a nice API.
* animations: CSS3
* templating: I don't do it, I prefer static pages and toggle sections with classes
* element filtering: better selectors (nth-child, nth-of-type, [data-stuff=''], etc)
* form serialization: either use event handlers and build it as you go or just use regular browser form handling
Currently, I use reqwest [1] for my HTTP requests. It's very small and is cross browser. In Dart, I just use the built-in libraries.
queryAll(selector).forEach((e) => e.value = value);
To me this is quite readable, and it's really nothing special about Dart, it's just that the dart:html library uses real Dart collections rather than the very unfortunate DOM NodeList.To go even further into jQuery territory, there are bugs requesting that queryAll() return an ElementList that has setters that effect every element in the list, so we could do this:
queryAll(selector).value = value;
I'm on the fence about that. It's short, but a little magical. I'm sure jQuery fans would like to have it though. document.querySelectorAll(selector).forEach(function (elem) { value = somevalue; });
Which is more obvious in intent and more flexible.Except this doesn't work, because that's not a real array, it's a stupid NodeList. :(
So you'd have to do:
Array.prototype.slice.call(document.querySelectorAll('thing'), 0).forEach(function (elem) { value = somevalue; });
ugh. Array.prototype.forEach.call(document.querySelectorAll('thing'), function (elem) { value = somevalue; }); _.each(document.querySelectorAll('thing'), function (elem) { value = somevalue; });
(But then I might as well just use jQuery, I guess)Can you tell me what does this line of code without checking what the f value is?
$(f);I.C.S.W.I.E.T.
jQuery is there to minimize surprises. Native API is magnitudes faster — yes. It is also divergent across browser runtimes. Then you code for special cases and test by hand, now you’re building your own jQuery.
Maybe we have better things to do.
And likely to get more so, now that Google has forked WebKit.
Losing support for IE 6 (or whatever) is no big deal, but support for both Android and Mobile Safari is critical.
https://github.com/jquery/jquery/blob/e80117adb49eff8f82140b...
BAD ASSUMPTION Just because they should doesnt mean they have or will anytime soon!!!
Have fun convincing my "stodgy old enterprise" to upgrade to IE9. They JUST upgraded to IE8! Yes, ideally no one should be using these crappy old browsers, and I champion this idea and all of the reasons why at work all the time. Rational arguments dont work in the kool-aid world of government. (Does it need to be said that I am looking for a new job?)
A lot of people browse the web from work, and so I dont think it is safe to ignore all of those crappy browsers yet.
(Enjoy.)
Of course you CAN do it... but do you want to?
http://dev.w3.org/2006/webapi/selectors-api-testsuite/level1...
Wish I'd known about this before. I've been using $('#main').get(0) when I didn't want a jQuery object. Which is all kinds of silly.
Until browsers can support all of that, I think we are a LONG way from saying goodbye to jQuery.
For all I know jQuery is saving me a ton of time when working on my prototype for the new side project. Last thing I want to do is to re-invent the wheel at my own expense :)
If JS performance were important, someone would write a jQuery -> js compiler and produced compiled js as output. But they don't do that, because once you benchmark the code, you find out that DOM is very slow, as johnbender mentioned.
I'm still used to hacking in vanilla JS, but when I want to write something longer than a hundred lines, I load jQuery. It's the only sane tool to reduce code size. It does it in a pretty disciplined, lisp-y way, too.
It's liberal use of the $(selector).f(x).g(y).h(z) style, which applies the function to the previous result, which is a collection, helps you code at a higher level of abstraction. No more loop structures!
It's not time to sunset jQuery: it's time to put more support for jQuery style functions into ECMAScript, so you can get better performance though parallelization, lazy evaluation, etc.
Yeah, let's get rid of it.
I focus more on tools rather than building things that matter in the end.
As is the idea that now that we have querySelectorAll, the DOM suddenly isn't a complete nightmare of an API.
before the library war started (prototype, jquery and mootools) i picked mootools for that exact reason, after so many lines written against that library i cant understand why jquery won in the end.
I hope you test your code like in 5 desktop browsers with different versions + 4 mobile browers with different versions , what , you dont ? well jQuery devs do ...
you dont care ? oh yeah your one of these mobile first , desktop last devs , then good luck with old versions of android browsers ...
I'm always amused by all these "death to this" , "death to that" , like it gives anyone any credibility...
So you get it folks , dont use jquery , reinvent the wheel like a true purist ,and remember to tell everyone "jQuery must die" , while professionals have code to ship.