Hacker News new | past | comments | ask | show | jobs | submit login
Why It's Time to Sunset jQuery (professionalaspnet.com)
64 points by jasoncrawford on April 14, 2013 | hide | past | favorite | 76 comments



Is this a joke? A huge percentage of the web is running with Jquery. Jquery targets a different set of audience - Ones that want to do more stuff with less code. This type of audience doesn't care about performance (mostly) because it helps them get things done.

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.php


Your jQuery:

  $(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...


    $.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?


It gets even messier when you find out one day you have to handle failures, or serialize data to send to that endpoint, or get notified on network events, or cancel an ongoing request, or etc etc etc.


My code is a response to neya's comment. It's not about short code or readability. It's about demonstrating that neya's example has completely unreasonable non-jQuery code given the jQuery code it is being compared against.


Your code is fine for this use case. But I'd have to bite my nails hoping it would work on browser 'X' for other use cases, which is simply not worth the headache. Cross browser compatibility is a real pain, you know? For me JQuery does it very well.

And good luck using your new ajax function :)


Drop support for old IE browsers, why are people still trying to fight to support them. I agree with the blog post, one day people will finally drop support for non-HTML5 browsers (IE8 and below) and they will see how easy it is to write clear, short native code that works fine in all browsers.

It will take time though as many people aren't even familiar with the native APIs.


You want to know why people worry about older versions of IE? Because a large enough chunk of their visitors still use those browsers. It's that simple.


    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.


Assuming you give your form elements names and the form an ID (unlike in the linked example) its trivial to get the query string using serialize and you don't have to fuss around with string formatting if you modify the form.

    $.ajax({
      url: 'ajax-example.php',
      data: $('#myForm').serialize(),
      success: function(data) {
          $('#ajaxDiv').html(data);
      }
    });


Yes, your argument is fair, but I just wanted to give you a fair idea of writing code in Jquery vs plain JS. Also, think about cross browser support - Why re-invent the wheel? There will always be some missing features that will not be compatible uniformly across browsers and hence the need for frameworks like Jquery.


I agree with your general point about the value of abstractions, but jQuery is rarely the bottleneck where DOM manipulation is concerned. Most of the execution time in browser applications is spent rendering/reflowing content. It's only sane to use the DOM API once you've shown that the jQuery JavaScript execution is a significant portion of total execution time relative to reflows.

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.


Is this a joke? A huge percentage of the web is running with Jquery.

I 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.


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.

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.


If only such a library existed...


There is also the problem of upgrading third party libraries as they may drop APIs or change their behavior leading to so many bugs that you spend more time fixing these issues then if you had written native code in the first place.


I mostly agree with your point that abandoning jQuery is premature but:

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...

[2] https://gist.github.com/noblethrasher/5383649


This is hilariously wrong-headed.

- 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.


> - 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.

Well, it depends. [1]

[1]: http://www.stevesouders.com/blog/2013/03/18/http-archive-jqu...


Those statistics weren't very helpful. It doesn't matter how many sites are using the CDN, it matters how may people visit those sites. If only 0.05% of sites used it, but 80% of people visited those sites, it would be worth using.


I've found memory leaks in long running single pages apps that were down to jQuery UI components so I wouldn't dismiss jQuery performance doubts so quickly.


jQuery UI is a whole different beast and there's a reason it's required separately.

Also at this point the base jQuery UI is pretty solid, but plugins are a different matter.


"I encourage you to give it a shot. Write your next application, library or just code for fun without jQuery. "

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'll find yourself needing a method to add or remove classes eficiently. So you'll rewrite .addClass() and .removeClass()

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...

[2] http://jibbering.com/2002/4/httprequest.html

[3] https://github.com/kriskowal/q


Client: I want this element to fade out. Me: No problem but only on browsers with CSS3 support. Client: What is CSS3? Me: Let me say it differently, it wont work on some browsers. Client: Why, is it hard to do? Me: Not really, but I would need to use an open source library to do it. Client: But don't you usually tell me that that's a good thing. Me: Yes but see yesterday I someone on the Internet said it should not be a mandatory feature. Client: You are fired.


The only major issue is with using CSS3 for animations (not transitions). IE generally handles it by adopting the new style state instead of animating.

http://caniuse.com/#search=css3


>So you'll rewrite .addClass() and .removeClass()

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.


classList won't work in IE < 10. XHR with promise is quite verbose. Transitions won't work in IE < 10. etc. These were examples, not a complete case list.

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.


Yes, but I'm not dealing with clients. I'm dealing with users of fun websites I make, and they aren't using oldIE. So I have a different set of requirements. I don't need jQuery, but you do.


It actually works in IE 8 and up (via shim): https://developer.mozilla.org/en-US/docs/DOM/element.classLi...


In fact, I think a case could be made that vanilla JS would encourage bad code.


Well said!


You know what I love about jQuery ? It's readable.

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.


I don't think so, for example:

    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.


Chain a few more commands onto that example and then we can talk about how readable the pure JS version is.


I've never liked chaining, and I hardly ever find a time when it's needed now:

* 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.

[1] - https://github.com/ded/reqwest


Just because you mention Dart here, I want to point out what this would look like in Dart right now:

    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.


It's even better with modern JS:

    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.


You don't need to call the slice method:

    Array.prototype.forEach.call(document.querySelectorAll('thing'), function (elem) { value = somevalue; });


And I could use underscore, a much more general-purpose library than jQuery to help me here, only 4kb. So:

  _.each(document.querySelectorAll('thing'), function (elem) { value = somevalue; });
(But then I might as well just use jQuery, I guess)


Everyone should be shimming ES5 array methods so your good example could quite happily run on older browsers too.


I'm sorry but four lines of code will never be "just as readable as" one.


Frequently four lines are more readable than one.


> You know what I love about jQuery ? It's readable.

Can you tell me what does this line of code without checking what the f value is?

    $(f);


Here's my answer:

I.C.S.W.I.E.T.


It might make sense to cherry pick jQuery features and build your own jQuery — if you absolutely need it, and absolutely can’t carry the whole library. In other cases I think it’s mostly just bikeshedding.

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.


"yes. It is also divergent across browser runtimes."

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.


IIRC jQuery 2.0 will have the option for custom builds.



This is good. Thanks :D I’m thinking along the line of what jQuery UI did — offering ability to customize a version of jQuery you can download from the site.


"first you need to make the assumption of a browser baseline. For me it is at least IE8, however that is quickly moving to IE 9 as most should upgrade to at least IE9, even stodgy old enterprises"

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.


I felt like the article did a good job of explaining the potential replacements, but failed to make a convincing case for why the perfomance benefits outweigh the simplicity of jQuery. There's a conversation to be had about balancing those two, but this post makes the implicit assumption that performance is king and never really addresses the tradeoffs between performance and simplicity/familiarity.


One of the many starters: http://www.greensock.com/jquery/

(Enjoy.)


Wow, I've never heard of GSAP before but it looks really promising, if you want to have a detailed control of animations for your app. I'd love to hear both plusses and minuses from someone who is using it production code.


It's awesome, but only useful on very specific animation-heavy projects. Otherwise it's quite overkill.


Considering that the highest version of IE that Windows XP can support is IE 8 and the large number of XP machines still out there - it will be fairly silly to not support IE 8 for at least a couple more years.


Have fun doing things like $('div').animate({opacity: '0.4', left: '10px', background-color: '#44444'}); in native js.

Of course you CAN do it... but do you want to?


You're right, it's better to write it with a CSS3 transition.


True, +1 for the nativeness. But we are still a short bit away from being able to reliably use CSS3.


That's IE's fault. CSS3 transitions really should've been in IE9.


Well, in the specific case of using native selectors (document.querySelector), I'm sold. It's supported very widely:

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.


The author's point is valid for selectors, but he is not considering the plethora of plug-ins that are built on top of jQuery and just work.

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 :)


JS performance isn't that important for most tiny apps. It's client side code and distributed.

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.


DOM manipulation and querying is a small subset of what jQuery does. There's ajax, event handling, dom creation from html fragments, animations, utility functions, size / position / offset calculators etc. And there are messy cross browser stuff in there.

Yeah, let's get rid of it.


Not knowing the details of jQuery 2.0's cruft removal, I wonder how much the performance gap is closed by a jQuery that doesn't need to deal with Really Old Browsers™.


Everything moves in cycle. Yesterday I started coding and found fragmentation to be the biggest issue so I thought I needed a framework to do anything reasonable. That issue got solved and I have got used to it. So today I am finding that performance is the issue. I again decide to dich the framework and start hacking it by hand. Tomorrow I find ...

I focus more on tools rather than building things that matter in the end.


I've seen a couple of people talking this way lately, and while we might be able to start talking about this in five years, the idea that after IE8 (or even IE9), we're past the point of needing a library to abstract away the differences between browsers is pure fantasy.

As is the idea that now that we have querySelectorAll, the DOM suddenly isn't a complete nightmare of an API.


jQuery exists because the native APIs available in browsers are not cross-compatible and suck at the same time. jQuery can be left alone once browsers revert the historical decision of just shipping a small core language.


I fear the OP conflates his usage with the rest of the world. Had he presented it as more of a 'this works for me' I'd have paid more attention. My own usage involves things I don't even want to re-invent wheel or no.


Why not build a tool that takes in a set of JavaScript files, analyzes them, and outputs a stripped down, compressed version of jQuery with only the features used in the input?


thats the exact reason i used to love mootools, but too many companies demand for jquery even if they arent going to do any coding.

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.


For people that worry about jQuery being to big, there is a lighter replacement for more modern browsers, doing (mostly) the same as jQuery: http://zeptojs.com/


if I understand correctly, the selling point of zeptojs is that it saves an enormous 20kb while breaking compatibility with half of everything out there?


jQuery is used a lot, because it describes a set of features and an interface that many other libraries build upon.


So now say "death to jQuery" and it makes you look cool trendy right ? or what ? because saying "death to flash" is so 2010 ?

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.


so you're saying that just by using jquery i dont have to test on every possible browser version and mobile too? i dont know what kind of jquery i been using but i do that everyday.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: