Do You Really Need jQuery?

Tweet

Apologies for the link-baiting title because this isn’t an anti-jQuery article. The same points can be made for any JavaScript library — including your own. However, jQuery is the favorite choice for many developers and some will add it before commencing any JavaScript work.

jQuery is an Abstraction

If you think web development is tough now, try developing JavaScript code in a browser from five or ten years ago. The typical problems:

  1. DOM navigation and manipulation differ. For example, Firefox (correctly) included whitespace in the DOM, IE6 didn’t. Therefore, you couldn’t depend on node.firstChild returning the same thing.
  2. Ajax was natively supported in most browsers, but an ActiveX control in IE (even though Microsoft invented XMLHttpRequest).
  3. IE had a different event model but even the other browsers had their share of inconsistencies.
  4. CSS2.1 support varied immensely.
  5. Animation could be difficult especially when coping with box model differences, form controls and iframes (IE6 placed select boxes and iframes above everything else on the page).
  6. Developer tools were rudimentary. Prior to Firebug, Firefox’s error console and IE’s clunky modal error box were the only built-in browser tools.

Developers had to write abstraction functions to get around these issues. jQuery, Prototype and MooTools evolved from the primordial chaos; the libraries smoothed over the cracks and provided useful missing features such as DOM selection from CSS selectors.

It’s important to remember that jQuery and the alternatives are written in JavaScript to make writing JavaScript easier. They’re not languages in their own right.

Going Naked

In 2013, the top five browsers are closer than they’ve ever been. The vendors have adopted standards and while some browsers may be missing certain HTML5 APIs, the core JavaScript tenets of DOM traversal, manipulation, event handling, server communication and CSS effects are well implemented and documented. If something works in IE10 or Firefox 23, you can (almost) guarantee it’ll be fine in Chrome 27 and Opera 12.

So why use a library when the problems it solves no longer exist? Naked JavaScript will always be faster than calling a library which abstracts the native call. In some cases, naked alternatives are also more useful. For example:

var i = $(".myclass");

uses jQuery to find all elements on the page assigned the class “myclass” at the point it’s run. However:

var i = document.querySelectorAll(".myclass");

will always be faster. In addition, if you used getElementsByClassname, the returned value is a live collection. In other words, the collection of DOM nodes represented in i will magically change when elements with the class “myclass” are added or removed from the page. The jQuery version must be run repeatedly to achieve the same result.

The primary benefit of the jQuery version is that it’ll work in IE6 and 7 (assuming you’re using jQuery 1.x). If you’re not developing for those browsers or have moved to jQuery 2.x, the main advantage is a simpler syntax — but remember you’re loading and parsing 30Kb of compressed script to provide that service.

Break the Dependency Chain

I’ve been using jQuery and my own smaller libraries for many years. Why? Mostly habit.

As a proof of concept, I decided to re-write the JavaScript code on a simple site which had some basic DOM manipulation, form validation and effects implemented using a small library. IE6 and 7 support wasn’t important, but IE8 had to work which meant I couldn’t rely on HTML5 form checking such as the required attribute. I still abstracted a few browser features but mainly for brevity, e.g.

function $I(id) {
	return document.getElementById(id);
}

The result: a 15Kb (combined and minified) JavaScript file was reduced to 3Kb using raw JavaScript code. An 80% saving.

Admittedly, it’s not proof you would achieve that outcome on other projects and a 12Kb saving would barely be noticeable. However, it did illustrate that I didn’t need all the functionality offered by the minimal library I was using. You certainly won’t be using all the functionality offered by jQuery even after removing unnecessary modules. Worse still, developers often use multiple libraries because they want specific features and/or plug-ins.

Never Say Never

I’m not saying you should never use jQuery. Nor should you underestimate the enormous development effort and assistance the library provides. Some level of native browser abstraction is always required no matter how you approach the code. Consider Ajax — you wouldn’t want to re-write XMLHttpRequest API calls for every server communication. A large client-side application will need a set of common components and jQuery or another library may be a good fit.

However, if you’re not supporting old IEs and want to provide the fastest, slickest, most compatible experience then take a hard look at the problem you’re trying to solve. For example, if you’re writing a cookie-handling utility, there’s no point in making that a jQuery plug-in or tying it to another library. Yet you’ll find cookie handlers throughout plug-in repositories even though it’s simpler and more effective to create a standalone module which works anywhere regardless of other code.

jQuery is a comforting blanket but, sometimes, it’s good to venture out naked into the JavaScript world. You’ll enjoy the freedom and learn far more about how browsers really work.

Coming soon: Naked Equivalents for jQuery Methods

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Lewis

    In the main jQuery is used by lazy people who do not understand Javascript or are unwilling to learn.

    I see it used as a cheap off the shelf solution so many times and it stifles creativity. How many times have you seen *that* jQuery gallery.

    In the right hands I’m sure it can be useful and treated well, but honestly Javascript is not that difficult and capable programmers are likely to avoid it.

    I can see the attraction and it does work very well, but it’s like cycling with training wheels on in many cases. Between jQuery and WordPress templates we’ve seen a huge influx of pro-webdesigners in recent years who do very little programming and very little design, it’s all generic samey noise with the illusion of technical ability behind it.

    • http://www.optimalworks.net/ Craig Buckler

      Part of problem is that developers add multiple page widgets without considering the consequences. A carousel which requires jQuery, a MooTools lightbox, a YUI form control, etc. Before you know it, you have 500Kb of JavaScript code which must be downloaded and parsed even though much of it isn’t required.

      Perhaps novice developers should be forced to use a 56K modem until they stop creating mammoth 1Mb+ pages!

    • James

      Lazy?! This might be fine for front end developers working on smaller projects, but not if your full stack(back-end,database,front-end,integration systems,etc.). This comes down to saving development time and leaning on developers/technologies that have encountered the same problems that you might not have faced yet or will face in the future.

      It’s not that we are unable, but can not simply justify the cost and time as it might not necessarily be value added and our customers more than likely will not pay for that extra time all in the hope of saving a few milliseconds.

      I agree for smaller projects or a specific task at hand, but to blanket it all? I don’t go rolling my own server side classes if one exists that I can derive to add the desired functionality. You would really be having to gain A LOT to re-invent the wheel.

    • NY

      Lazy == efficient

      If you are saying that it is lazy to use things that already exist then I think next time you need tires for your car you should get a chisel and a giant rock and carve your own wheels. Would you do that? No.

      I personally believe the more “lazy” a coder is the better. That means they are using their resources correctly. Being lazy doesn’t mean you are a bad coder by any means.

      Just my 2 cents.

      • http://www.optimalworks.net/ Craig Buckler

        Don’t forget that jQuery doesn’t do anything you can’t achieve through native API calls or writing a few small custom functions. Writing less code is efficient, but always including a library for the sake of it is lazy.

      • http://niteodesign.com Blake Petersen

        Wow, talk about controversy!

        But, unfortunately, a lazy coder is the worst and is probably much less efficient because of it. Cowboy coding is lazy, and is inefficient. Inline-css is lazy and inefficient. Using jQ as a crutch, never taking consideration as whether it’s needed and just using it by default, is lazy and inefficient.

        Efficiency should not equate to how easily you were able to perform as a developer, it’s how efficient the resulting application is. If you’re pumping 30kb down to the user along with a plugin to do something special, like cookie handling, you are essentially forcing an extra 40kb to the page weight simply because you’re lazy and don’t want to write, for example, a simple function to handle cookies yourself (or snake one off StackExchange).

        Sure it took you less time on your end, and you could say it’s more efficient for yourself, but you are not coding for yourself, and the laziness creates inefficiencies for the audience, which will work against any conversion you hope to make on your site. This would mean you are the worst kind of coder. You are making your application worse for the sake of making your “process” quicker. It’s actually an extremely self-oriented way to looking at this and entirely wrong.

        If you’re trying to get hired anywhere, don’t make that point. You won’t get called back.

      • http://www.optimalworks.net/ Craig Buckler

        Well put, Blake!

      • NY

        @blake

        This article explains more along the lines of what I meant (except it is engineering and not coding, but same concept)

        http://www.eetimes.com/electronics-blogs/pop-blog/4374110/Most-engineers-are-lazy-and-that-s-often-a-good-thing

      • http://www.twitter.com/theoutlander Nick Karnik

        @Blake – It’s crazy how many times I’ve had to deal with people with that attitude. I like how you put it!

  • http://www.drakeintelgroup.com Karl J. Gephart

    Learning JS from a CSS background, it seems that jQuery is written so much more concisely. I appreciate being able to use it whenever I can in place of some JS functionality. But I haven’t really looked at backbone or other libraries yet to compare it to. It almost seems like CSS is trying to move in on JS as well, particularly in the area of effects and animations.

    • http://www.optimalworks.net/ Craig Buckler

      jQuery is only concise because it provides JavaScript methods to do exactly that. In other words, it provides pre-built functions which you’ll find useful. However, it’ll also provide a lot of stuff you won’t find useful…

    • Jeroen

      The problem is situated in your first line: ‘Learning JS from a CSS background’.

      JS is a programming language that today is mostly used inside the browser (it is however becomming more and more used on server-side; node.js). Using the Dom API, Javascript can manipulate the DOM. But it wasn’t made with that in mind.
      I made the same mistake 5 years ago, looking at javascript as a language of the DOM to manipulate some CSS, and most of the ‘tutorials’ out there didn’t deny that…
      I completly misunderstood Javascript, so I started using libraries like jQuery, it seemed they made javascript better.
      Karl, don’t use backbone as you would use jQuery. They have 2 completly different purposes.

      But then I started looking deeper into JS and started noticing it is so much more. I advice everyone to read the 3 guest articles on David Walsh’s blog: http://davidwalsh.name/javascript-objects and the following article: http://javascript.crockford.com/javascript.html

      @craig: good article!

  • http://www.ecru.co.uk Matt Williams

    Do you not feel that delivering jQuery from the Google CDN is advantageous?

    • http://www.optimalworks.net/ Craig Buckler

      Retrieving jQuery via a CDN has the advantage that you’re serving content from two domains (most browsers permit four concurrent HTTP requests from the same domain).

      However, loading from a CDN is only part of the story. When jQuery or any other JS file is loaded, the browser stops whatever else it’s doing to parse and run that file — a CDN doesn’t necessarily make loading faster or “free”.

      My point is: do you need it? If you’re doing a little animation and form validation, CSS3 and some raw JavaScript is more efficient than adding a large library.

  • http://ohdoylerules.com James Doyle

    I made a tiny library that maps queries like $(‘#element’) to their native DOM get commands. So in this case $(“#element”) would be mapped to document.getElementById(“#element”). The best part is that it comes in at about 240bytes!

    https://github.com/james2doyle/saltjs

  • http://www,yankeeweb.com KM Tibbetts

    Craig, querySelectorAll does not return a ‘live’ selection. Otherwise, good article.

    • http://www.optimalworks.net/ Craig Buckler

      Doesn’t it? Wow — you’re right. That’s a shame. I wonder why that’s inconsistent with getElementsByTagname and getElementsByClassname?

      • http://ajax.wikispaces.com/functional_comparison Amanda Morgan

        Probably not a LiveList for performance reasons.

      • http://www.hmlong.com/ Michael Long

        This is just another justification for the “roll your own” vs. library argument that’s been going on ever since we started programming computers.

        And I think the confusion over querySelectorAll underscores a point in regard to rolling out your own “simplified” code: That it’s fairly likely the jQuery library team understands browser behavior and JavaScript better than you do.

        And as such you’re probably going to be spending more time supporting and debugging your code that you think you will.

      • http://www.optimalworks.net/ Craig Buckler

        It’s not. I accept I made a mistake in presuming querySelectorAll resulted in a live collection, but it would have been apparent the moment I tried using it in that situation (I have to admit that I’ve never found live collections useful in day-to-day development). All the browsers (IE8+) implement it the same way — there aren’t any major inconsistencies.

        jQuery is a great library and, if you’re supporting IE6/7/8, it’s almost essential. However, you seem to be of the opinion it’s doing something sophisticated. Parts are (I tried writing a Sizzle-like selector engine and it’s tough), but much of it is a shim on top of existing native JavaScript. For example, jQ2 uses querySelectorAll when you select nodes.

        Your last sentence makes a very dangerous assumption. I’ve been using my own libraries and jQ for years and the time difference is usually negligible. You get problems in both, but it’s much easier to debug your own code.

        I’m not saying you should never use jQuery. I’m saying you should assess every project before assuming jQuery is the best fit.

  • http://www.markadrake.com Mark Drake

    Using libraries for development is common for small teams and large; as web sites become more application-like we are going to see nothing but an increase in the use of jQuery and friends.I couldn’t imagine maintaining a huge library of code dependent on work-arounds and quirks between browsers while managing a team of 5 or more developers building a web application. jQuery is at the center of everything we do, for now.

    I feel it important to mention that you can build your own version of jQuery only including the things that you actually need for your project. (https://github.com/jquery/jquery/#readme)

    Also 2.0 is even more lightweight now, but dropped support for IE8 which still a big portion of the market for some of our clients, more-so for intranet sites.

    • http://www.optimalworks.net/ Craig Buckler

      “I couldn’t imagine maintaining a huge library of code dependent on work-arounds and quirks between browsers”

      That’s my point: what work-arounds and quirks? IE6/7/8 — absolutely: use jQuery 1.x. But if you’re supporting IE9+ and the latest browsers, a library may be overkill.

      • http://www.hmlong.com/ Michael Long

        The only place you can be fairly positive that you’re on the “latest” browsers is if you’re on a corporate intranet where a specific browser/version may be mandated, or if you’re targeting smartphones and tablets on iOS or Android.

        And again, most people don’t implement jQuery just for the sake of implementing jQuery. They want jQuery UI or they want to use one or more of the other tools built on top of that platform.

      • http://www.optimalworks.net/ Craig Buckler

        I totally agree but, if you’ve switched to jQ2, you’re dropping IE6/7/8 whether you realize or not.

        However, I think many developers DO implement jQuery (and/or other libraries) for the sake of it. That’s the problem.

  • Zlati Pehlivanov

    On the question. I think yes, we still need jquery if you really want support on more browsers for stuff like forEach or map. Personally I use it for trivial stuff like ajax, promises, DOM altering and events binding. I don’t like when people are using it for adding inline css, but I have to agree that it’s very easy for a newcomer to start making something. Even trivial thing like fadeIN, fadeOut with a callback is cool. After all, javascript libraries have something in common, to make you write less trivial code.

    • http://www.optimalworks.net/ Craig Buckler

      Isn’t forEach and Map better handled by a small custom function? I have a rudimentary forEach which works on arrays, collections and objects which is three lines long. Even Ajax, DOM and event handling rarely require more than a few dozen lines to make them easy to use. Animation? Use CSS3.

      At one time, libraries certainly made life easier. However, I’m beginning to wonder whether they’ve become an alternative syntax for the sake of it.

  • Ran

    One issue you did not mention comes to mind: code consistency and uniformity. Handing off a site to another developer is easier when you are using common code libraries like jQuery. If you are developing using code you have devised youself – then the next developer in line will have to invest a lot of time and effort in order to understand your custom functions. Using a code library is not only for “lazy developers” as claimed here. Using code libraries (and platforms, templates, etc.) help speed up development and code management.

    • http://www.optimalworks.net/ Craig Buckler

      That is a good point: jQuery is well documented and I agree that could help larger development projects. That said, I bet you could remove many of the modules without impact.

      • Jeroen

        Code consistency and uniformity has more to do with the program skills of the devs.
        If you write decent code, with decent documentation there is no need for a certain library.

  • pippo

    >However, if you’re not supporting old IEs and want to provide the fastest, slickest, most compatible >experience then take a hard look at the problem you’re trying to solve. For example, if you’re writing a >cookie-handling utility, there’s no point in making that a jQuery plug-in >or tying it to another library

    Bit of a weak theory here.
    It is very unlikely that all you need for your site/app is a cookie-handling utility.
    Very soon you will need a lot of interacting complicated components that you have to write, test and mantain on your own.
    Jquery provides them out of the box. Jquery is integrated in a lot of frameworks (server or client side) not to mention Bootstrap.
    I still write a lot of js on my own, but I try to evolve from some existing code, jquery just comes handy every time.
    Plus my js knowledge does not come any close to those guys who write libraries, even if try hard.
    Those guys who have the skill to write better js, certainly have some good reasons not to use libraries.
    The rest of the world just thanks and download libraries.
    If you are not one of those guys and you are concerned about performance you should consider CoffeScript instead.
    Anyway, does not your consideration apply to any programming language?
    Naked is faster than framework in terms of execution but is it faster in terms of development time?
    Frameworks foster standards and thus code collaboration much more than witty one-liners, this is no longer debatable nowadays
    (I think)

    • http://www.optimalworks.net/ Craig Buckler

      jQuery is included everywhere but that doesn’t mean everything needs it. I rarely use it in basic WordPress templates, for example.

      The difference between many JavaScript frameworks and other language libraries are:

      1. jQuery and similar libraries do not provide missing functionality: it’s already there. They just make it a little easier to use.

      2. Adding superfluous code to a web page impacts performance. That’s not true for many other languages.

      Of course jQuery is handy, but it’s very generic and doesn’t perform specific library-like tasks (like something such as three.js which most of us would struggle to replicate). Is jQuery always necessary in a post-IE8 world? Probably not.

      • http://www.hmlong.com/ Michael Long

        Couple of things.

        One is that there are a lot of sliders, tabs, accordions, modal dialog handlers, portfolio image handlers, validation scripts, and so on that are built on top of jQuery. Not to mention jQUery UI. And each one is smaller than it would be if it had to replicate that dependent functionality on its own.

        As such, incorporate just one or two of those things into your site, and your aggregate savings is probably less than it would be otherwise.

        Second, jQuery and a few other libraries are hosted by Google and as such available through Google’s CDN. So if you use Google’s links, those routines will be delivered a lot faster than your own homegrown versions. And that assumes they haven’t already been downloaded and cached when the user visited some other web site.

        Third, time spent debugging and rolling your own version is time spent not improving your site’s core functionality.

        Finally, I like that idea that was floated recently. If you’re THAT concerned with the impact of downloading a 30K library…. then just use ONE less image on your web page.

      • http://www.optimalworks.net/ Craig Buckler

        Thanks Michael. I agree there are a lot of things using jQuery as a core (whether they all should is another matter). So, if you’re using a number of these components, the saving will be reduced accordingly — although probably not as much as you think. Also, picking widgets from different libraries is a waste of resources.

        A CDN only helps in delivering the script faster. The browser must still parse that script on every page. In other words, the whole jQuery library is executed before any of your code can run.

        Your third point: why are you rolling your own library? You may create a few shortcut functions, but you’ll be using the native APIs. jQuery uses them and, until recently, it worked around the incompatibilities in IE6/7/8. If you’re not supporting those browsers, there are very few inconsistencies between the browsers.

        I totally agree that removing a graphic could have a far bigger impact on page weight. However, as good web developers, we should be striving to remove weight anyway — whether it’s HTML, CSS, images or JavaScript. This article just concentrates on the JS side.

        However, I would re-iterate that 30Kb of JavaScript is more expensive than a 30Kb image — the browser needs to parse the code and halt all other processing until it’s complete.

  • Pedro H.

    I have been around in the web developing business ages before I heard about jQuery. I was already doing naked JS in IE 5.5 and never had the need for a library such as jQuery. At least, not until Firefox was launched. That’s I was starting to have nightmares about cross browser issues. For me, jQuery was a life saver, but I dare to say I find jQuery these days a little bloated. Sure, I can build my own jQuery, but I never know when I lack a particular feature.

    @Lewis: You mentioned that JS in not that difficult. I can agree to some point. But please be reminded that for many of us programmers is not about being lazy. It’s about learning curve. And typing… Let us compare then JAVA to PHP. Which is smaller? echo (‘hello world’) in PHP or system.println(‘hello word’) in JAVA after typing some more code to use stdio? Well… I’ll bet that typing a css query in jQuery sure beats typing document.getElementById(”).

    @Craig: To reply to the post: Yes I need jQuery, but I don’t need it to be bigger filled with functions i’ll never use and that I can mix in good ol’ naked JS to do the job.

  • http://ajax.wikispaces.com/functional_comparison Amanda Morgan

    If you’re into “Naked Equivalents for jQuery Methods” then you should check out this wiki that’s supposed to list equivalents for common tasks done using plain JavaScript and using various libraries like jQuery, Dojo, Mootools, MochiKit:

    http://ajax.wikispaces.com/functional_comparison

  • http://www.ihatetomatoes.net Petr Tichy

    Haha, interesting conversation. I don’t see anything wrong on using jQuery as your main JS library instead of writing naked code. There is a huge community behind jQuery and great learning resources, which makes jQuery quite easy to pickup for anyone.

    I have seen a lot of geeky developers using pure javascript and writing a lot of unnecessary code which was a nightmare to maintain and update.

    Use whatever tool or library you want, as long as you write efficient and maintainable code.

    • http://www.optimalworks.net/ Craig Buckler

      Don’t assume jQuery magically makes code more efficient. You can do dumb things no matter what library you use, but jQuery makes it less obvious (see example above).

  • http://brianswebdesign.com Brian Temecula

    Before I used jQuery I did some work in naked JavaScript. Even though the things I created seemed to work, I feel like I have more security when using jQuery. I can’t possibly test in all browsers, even though I normally test in multiple and one multiple O/Ss. It’s pretty rare that I create something with jQuery and find that it’s not working for a single browser. It more or less works or it doesn’t, which simplifies my job. The worst feeling is when you are proud of some work you did and somebody points out that they are looking at your site on browser X on O/S Y and having problem with Z.

    • http://www.optimalworks.net/ Craig Buckler

      Certainly where IE6/7/8 are concerned, jQuery is very useful although, on the flip side, I do think it gives you a slightly false sense of security. There will always be issues and using jQ is no substitute for rigorous cross-browser testing.

      However, jQuery 2.0 is for IE9+ which is closer to Firefox and Chrome than IE6/7/8. It still handles some quirky stuff in older webkit browsers, but there are fewer reasons to use it. It could be argued that it’s an unnecessary overhead since naked JS will almost certainly result in less code.

  • http://computer-consulting.com Terry A Voss

    Part of jQuery it seems is trying to improve an old language with terms that are long and unwieldy…words are important and descriptive…classes and objects…versus spaghetti…

    • http://www.optimalworks.net/ Craig Buckler

      jQuery provides shortcut methods and chaining which simplifies constructs, e.g.
      $(“.myclass”).show().css(“color”,”#000″).on(“click”,runfunc);

      Very efficient. Or is it? It’s quick to write but you have the overhead of three loops rather than one and it may be better to apply a single event handler to the page or a parent node rather than each element.

      That’s a little unfair on jQuery because crap code can be written no matter what language or library you’re using. However, it’s quick to write so developers often mistake it for “efficiency”. A little knowledge of the underlying processes will help you write better jQuery and/or JavaScript code.

  • Mikey

    Where I work, our clients use old browsers. Why? I do not know. I find that using naked JavaScript and making it work on all browsers is such a pain. Once I started using jQuery, my workload became so much easier. Isn’t there a saying “don’t re-invent the wheel”?

  • http://damil.co.uk Dave Leach

    Thanks Craig, and I agree with your premise that jQuery bloats the page with a lot of stuff that it doesn’t need, and won’t use. Sadly though, for now – and I guess for some time to come – IE 7/8 will be with us and will present the cross-browser issues that jQuery helps us to solve. Worth bearing in mind for future though – and it gives us time to learn to use JS properly :)

  • Alfredo

    It just happens that many things that I want to achieve, someone has already done using jQuery. So, why reinvent the wheel???

    • http://www.optimalworks.net/ Craig Buckler

      Yes, and someone else has already implemented it within JavaScript. You’re not re-inventing the wheel: jQuery is the spare tire you may not need to take on every short journey.

  • http://terrym10@me.com Terry

    I wouldn’t consider using naked javascript if a library is available. We’ve tested and Craig is right. Speed does increase, files are smaller. But, we don’t bill on smaller file size. We build on functionality and on making sure that functionality is rock solid.
    Jquery is wonderful for us in time savings (monetary considerations always rule). Time is money.

  • http://heera.it Sheikh Heera

    Well, when I need an abstraction layer to achieve similar behavior on every browser then I need to write a library or can use an existing one. So, what is the benefit of writing your own whereas you can use a library like jQuery without any extra headache (you don’t have to maintain it).

    Till IE8 is alive I can’t even think about jQuery 2.0 and in this case naked JavaScript is so far a way. We don’t develop for ourselves, instead we work for our clients and a client doesn’t want to lose a single visitor for lack of browser support.

    jQuery is not necessary but consistency is most important thing in your work/code and you should always use such a thing that other developers can understand and familiar with.

    • http://www.optimalworks.net/ Craig Buckler

      jQuery isn’t a zero overhead if you regularly update to the latest version. Incompatibilities are rare, but that doesn’t mean you don’t need to test.

  • Grisha

    Naked JS as good as jQuery and better?
    Just till the next stupid browser war! and then what? We will be looking where is our jQuery lost?
    Attempts to kick MS IE can clearly be seen in this article.

    • http://www.optimalworks.net/ Craig Buckler

      What next browser war? All the vendors are working together (mostly). There are no competitive benefits to building a browser which is different to the others.

  • Tony

    Is there a SASS equivalent for jQuery? It would be really cool if one could create mixins to handle only the plugins you were using for your site, which would compile into a nice, compressed custom jQuery library.

    @Blake: your comment reminded me of something my boss always says: you can have it cheap, quick, or high-quality–pick two!

  • Sean B

    I’d say fanatics one way or the other are the worst. Use your judgement. What is pragmatic? Loading an entire library merely for DOM utilities? No. Reinventing HighCharts while building a large enterprise scale UI for which charting is just one of many components? Also no. There is robustness in the world, nurtured by folks focusing on the micro (widgets) so you can focus on the macro (complete UIs). Set aside the vanity of native coding for it’s own sake. It does have its place. But remember what you were hired to deliver, and use the best tools available to you to accomplish that goal.

  • http://afterlight.com.au AussieJohn

    I’m a big fan of JavaScript. By itself or as an implementation in various libraries.

    It’s hard to get around the fact that jQuery bloats your page however there are several good arguments for using it.

    * If you work in a large dev team – jQuery can save you considerable time as a lot of devs have familiarity with it
    * As Craig pointed out, if you need to support Old IE (6/7/8) then jQuery can be a wonderful tool because of its abstractions.
    * Testing jQuery get a vast amount of testing including all those pesky cross browser issues.
    * It’s well documented (there’s nothing worse than using a framework and trying to find what parameters a particular function needs and it not being documented anywhere. I’m looking at you KnockoutJS.)
    * Plugins – let’s be honest – if you need something done and don’t have the time to write it yourself, there is probably a jQuery plugin for it.

    Having said that, and noting that I have been working with jQuery for almost 6 years now, I do believe that if you need something simple for your site, then use a Micro framework that can achieve the same thing. If you only need some simply DOM manipulation and Event Handling for example, don’t load in 91kb of jQuery. Need some simple animations. Don’t load in 91kb of jQuery. (etc.)

    I find myself scouring GitHub and sites like MicroJS.com for small libraries when I only need some simple DOM manipulation/templating/Event Handling, etc.

    So here’s some benefits to using Micro JS frameworks.

    * They’re lightweight (great for Mobile!)
    * They have abstractions and quite often decent browser support (your mileage may vary though)
    * The more popular ones get a decent amount of testing (by the community)
    * They save time because you don’t have to write abstractions and deal with browser weirdness.
    * Did I mention they’re lightweight.

    As I’m sure a few folks have pointed out already, make an informed and pragmatic decision about what your project needs. Try to use frameworks with good documentation. Write good documentation if you make your own frameworks.

  • http://www.appgen.com/songcat Pete Januarius

    I reckon there is a huge case for libraries such as jQuery. Otherwise people will just start writing proprietary stuff again which will have to be learnt by every new developer to the team.

    I was hoping we were beyond that ‘evolutionary’ stage.

    I have written several highly complex Javascript apps with jQuery in the Banking and Broadcasting industry and I for one would never leave home without it.

    Also as other people have pointed out – 30k is not going to sink your company. Just be intelligent with your page design. Small code is not the be all and end all of development. It seems to be a huge thing to many programmers. No – write a system that is maintainable and extendable and as simple as possible to hand on – not one with terse code no one can understand. Most systems are complex enough without us devs adding to the complexity.

    Cheers!
    Pete..

    • http://www.optimalworks.net/ Craig Buckler

      “people will just start writing proprietary stuff again”

      You mean they’ll start using JavaScript to write JavaScript code?! As browsers evolve, we simply won’t need helper libraries which smooth over the inconsistencies because those inconsistencies won’t exist.

      The 30Kb carries far more weight than other files too. The non-minified jQuery is 300Kb — that must be parsed on every page before the browser can run your code. That’s not a problem if you’re using a significant proportion of it’s functionality, but few people do.

      • http://www.appgen.com/songcat Pete Januarius

        I don’t use it to smooth over browser inconsistencies. I use it because it is a good library and I am used to writing complex things quickly with it including plugins and ui widgets. I also use most of the api.

        I agree with you in terms of small sites, one pagers…etc – no point using jQuery here. But for something that is going to be 10 – 50K lines of Javascript, the reality is you need to pick your library and use it. What a nightmare the frontend code would be if everyone went back to ‘using JavaScript to write JavaScript code’ as you put it. That’s the reality.

        I can’t remember seeing a job advert for a frontend dev in the last year that said: “must use JavaScript to write JavaScript. No libraries allowed’. Actually the reverse is true.

      • http://www.optimalworks.net/ Craig Buckler

        You use most of the API? Really? Even animations which are (normally) better handled by CSS3?

        I’m not saying you should never use code libraries. However, jQuery is very generic and the browsers have caught up (querySelectorAll, forEach, CSS3 animation etc). There are fewer reasons to use it than there were when oldIEs ruled.

        Why would it be a nightmare if everyone went back to writing JavaScript modules in JavaScript? Sometimes it makes sense to use native APIs and it means modules are compatible with whatever library you decided to use.

        If you understand JavaScript and the native APIs, you’ll have a better understanding of how browsers work — it’ll make your jQuery code more efficient too.

      • Robert

        The 30Kb carries far more weight than other files too. The non-minified jQuery is 300Kb — that must be parsed on every page before the browser can run your code. That’s not a problem if you’re using a significant proportion of it’s functionality, but few people do.

        Craig, I couldn’t find this thread earlier. But someone else I just bumped into, had it bookmarked.
        Your assumption/understanding that jQuery is parsed on every page before the browser can run your code is not up-to-date anymore :
        http://stackoverflow.com/questions/1096907/do-browsers-parse-javascript-on-every-page-load

      • http://www.optimalworks.net/ Craig Buckler

        Admittedly, modern browsers have bytecode caching facilities. However, the point is that the code must execute on every page. It doesn’t “know” what it’s going to do — it could be writing to the page when a random condition is encountered. Therefore all other processing must be halted while it runs.

        jQuery is no different — the browser must execute the code to ensure objects and methods are available in memory once you try to use them. It’s a fair amount of code to wade through and, while it won’t be a problem for a modern PC, it can be noticeable on slower devices.

      • Robert

        must be parsed on every page before the browser can run your code.

        the point is that the code must execute on every page.

        Parse before, or run/execute?

        Safari is not even bothering with caching compilations. What they mention, compilation being less than 2% of code execution, will be a similar number for every browser. On top of that, other browsers do cache compilations and parsed JS code. So this “whopping performance hit” is only once.
        Quote about Safari:

        currently, code generation is a
        trivial portion of JS execution time (< 2%), so we're not pursuing
        this at the moment.

        Pure JavaScript will be faster, but gives you the headache of testing for cross-browser compatibility yourself.
        Also, pure JavaScript code must be compiled, and also halts execution while it’s running, just like jQuery. It’s not like every byte and bit of jQuery is executed whenever you call one of its API’s after parsing/compilation. It will no doubt be a bit slower (having to mop the floor behind browser X+Y+Z). But can you tell if you’re waiting a few tens of miliseconds longer?
        Also, people with slower devices, they know that the device is slow. ;)
        And old and ageing very, very slow iPhone 3G (not 3Gs) I have lying about, still makes a good reference point for page load speed measurement (that is, if the browser sometimes doesn’t crash during page load, and dumps me back to the phone’s home screen.)

      • http://www.optimalworks.net/ Craig Buckler

        There are two general phases in JavaScript execution. First, JavaScript engines are faster than many interpreters because they do some compilation first. However, the code cannot be fully compiled owing to the nature of the language (loose typing, eval, etc) and because it’d cause a noticeable delay before running.

        Second, the code must run immediately after download (you can defer/async, but it will still execute at some point). While this happens, the browser halts all other activities. In old days, it could freeze the application. They’re a better today, but the execution phase must occur because the script could change the page before other assets are downloaded.

        This happens no matter what script you’re using; native JS, jQuery, YUI, etc. All must be parsed and executed when encountered. In the case of jQuery, it’ll need to ensure all functions and methods are available to other scripts — it won’t run them until they’re needed, but must still wade through a significant quantity of code to see if anything needs to be done.

        My main point: in the areas where the jQuery core helps (DOM, events, animation, Ajax, utilities), the modern browsers are consistent. You may struggle with more recent HTML APIs, but they’re not supported by jQuery anyway. Besides, jQuery never has and never will negate cross-browser testing. If anything, installing updates will increase the testing requirement.

    • Jeroen

      A lot of people seem to forget than jQuery is a library of functions designed to manipulate the DOM. As long as you use it for that there is nothing to hold against you.

      Once you start using and tuning it to write ‘Banking an Broadcasting’ applications I shrug.
      You simply mean you are writing javascript code that uses jQuery for its frontend? I hope so…

      And what do you mean with highly complex javascript apps? Up to now I still have to come accross a serious big javascript application that uses jQuery. And with big I mean Facebook, soundcloud, GA, Raventools,… big

      In your last sentence you talk about ‘terse code no one can understand’. Javascript is one of the best understandable languages once u master it. jQuery doesn’t improve how your code reads. The devs do, crappy devs write crappy code, jQuery or plain ol’ JS. The will write crappy code.

  • Ashmawi

    Well, writing your application in Assembly language will definitely result in a faster application than writing it in any other language except binary if one could do, but this doesn’t mean that we measure only this factor, in business you will have to put all factors together and see whether the sum is positive or negative. Certain critical applications will need to go up to that level, because the performance factor is by far the highest priority among other factors such as (Time/Cost, maintainability, appearance, etc.). but this is not the case for the majority of applications. The same thing here.

    The problem is if you have a large web application where you depend heavily on Javascript, you may end up writing over the 30K of code to handle all what your pages need, or a little bit less; and if you are using any plugin which is using the jQuery, you will load it anyway, and it will be cached once loaded, moreover if you load it from one of google’s CDNs it might be already loaded in the user’s browser cache. So using jQuery would not be that costly in terms of performance, and you would definitely do more to your site/application when you have such a powerful tool in hand, and whoever comes to continue on your work will have a less painful life :)

    Just an opinion :)

    • http://www.optimalworks.net/ Craig Buckler

      There’s a misconception jQuery is a high level language compared to low-level JavaScript. It’s not: jQuery is a set of useful JavaScript functions which build on existing JavaScript APIs.

      If you’re not supporting oldIEs, there’s far fewer reasons to use abstractions. The point is: you may not need a generic 30Kb library in the first place.

      • Ashmawi

        I just mentioned the low level and high level languages scenario as an example for the trade off between performance and other factors like the time, cost, etc. just to illustrate my point.

        I do agree that pure javascript could be enough and more efficient in certain cases, I would do so but only when I’m writing a single script to perform a specific task, or I’m developing a very small website where I need to perform very few things in javascript. but once it gets bigger I personally would prefer to save my time and use a library that can make my life easier :)

        I might be a fan of jQuery, but still I learned many new things from your post anyway, and I’m always following your topics, so thanks Craig :)

  • http://www.xoogu.com/ Dave

    For me, the main benefit of jQuery is in DOM manipulation. jQuery’s ability to parse a string of HTML and add it to the DOM saves so much time (and text) over using document.createElement and setAttribute. I seem to recall that with XHTML you need to use document.createElementNS and setAttributeNS, which are even longer.

    Another issue I sometimes come across is scope creep. I might start off with a website with pretty basic needs. But then later might want to add some enhanced functionality. If you add jQuery to make adding the extra functionality easier, of course your naked js will still work. But it would probably be less code in total if your naked js was written in jquery as well. So you can either spend time re-writing your naked js to jQuery, or otherwise serve more js than you would have to if you’d just written it all in jQuery from the start.

    Regarding the native equivalents of jQuery methods, Lee Brimelow has already beaten you to it: http://www.leebrimelow.com/native-methods-jquery/

    I do agree with your point, just I think that actual number of cases where naked js would be preferable to jQuery are pretty low.

    • Ari

      @Dave wrote : “…I do agree with your point, just I think that actual number of cases where naked js would be preferable to jQuery are pretty low.”

      Thank you, Dave! In the final analysis, it’s all about trade-offs.

      Let us not forget that JQuery libraries can and will be optimized as new comers, like Micro.js? — demonstrate better efficiency. When this happens, jQuery interface will likely remain the same but code size and efficiency will improve.

      Finally, processor and memory speed continue to get better and cheaper– leaving application development and maintenance as the key cost factors. (Hmmm… Craig, haven’t we been here before? It’s deja vu all over again!)

  • James

    @Blake
    I agree with your example with the cookies and other custom segments and other areas where it makes sense, but I think you are misunderstanding my point. it’s just simply a ludicrous philosophy to say that it’s the worst kind of coder by making the process quicker and more efficient. It’s not for my sake to make the process quicker, it’s for the customer’s sake (and wallet).

    On a larger project, would a customer rather pay NNNK and take a full year to develop because we wrote all of our own custom code? Or would they pay NNK and get it done in 6 months with the utilization of some existing sources with the POTENTIAL, and I severely stress potential, of a small trade off of a little performance and still have a rock solid application that serves their business requirement and makes their end users happy?

    If the customer is made well aware of the trade-off and willing to take it for reducing cost and time, who are you to say “No No, you’ll pay twice as much because we are too arrogant to utilize other resources”. It’s the customer’s decision because they are paying you, not the other way around.

    In my opinion, it’s simply stealing money from your client and just plan thievery!

    ‘Nuff said.

  • http://www.dzpage.com Mourad Hamoud

    I don’t think I’m ready to drop JQuery, I will wait ;-)

  • http://www.fmrwebdesign.com Raja

    Not sure about everyone else, I have been using jQuery for a while and now I feel myself so much dependent on it. The other day I had to fix a bug in a piece of script that was written with jQuery and for the first time I realized that I have gotten so used to it that I have almost forgotten the functions included in the core javascript.. Also, is performance really that much of an issue? I doubt it. I love it way too much, can’t let it go just yet :-)

  • Robert

    I already read part 2, but I felt this response was more suited to this discussion (part 1).

    I agree with everything what’s written in this article, except for the last line of this excerpt :

    In 2013, the top five browsers are closer than they’ve ever been. The vendors have adopted standards and while some browsers may be missing certain HTML5 APIs, the core JavaScript tenets of DOM traversal, manipulation, event handling, server communication and CSS effects are well implemented and documented. If something works in IE10 or Firefox 23, you can (almost) guarantee it’ll be fine in Chrome 27 and Opera 12.

    And this is why :
    These same vendors have given themselves a name in the past with “I did it my way” approaches, and ignorance.
    Like male dogs they were barking, jumping up, digging, rolling in dung, fighting, and urine marking.
    Causing lots of extra work and late nights for thousands of developers to fix/prevent broken sites. (BTW, broken browsers is more appropriate.)
    Extra work = Extraneous vendor specific checks, assumptions, and wild guesses (all in code).. More often the checks were up to 5 times bigger than the 1 or 2 lines of code that they were trying to execute, or prevent from executing.

    The top 5 might be behaving right now, but there is no guarantee that they will keep doing that.
    I love JavaScript, and would love to code JavaScript without jQuery & Co, but I’m not willing to take the risk of being bitten again.

    The good thing with jQuery & Co is, that if just one of the top 5 starts misbehaving again, and breaks x number of sites, just 1 jQuery update will fix all/most sites involved. Linking to “code.jquery.com/jquery-latest.js”, or for more control a simple option to enter the exact jQuery version number in the site admin back-end will do. (Sometimes jQuery needs a down-grade.)
    If there are a few sites left broken, the number will be far less than with bespoke code.
    And with my bespoke code, I would have to fix them all manually by visiting the sites. Because I haven’t come across one client yet who’s willing to let the good functioning of their site(s) depend on linking off-site to my bespoke JavaScript library, on my server. ;)
    (My JS library is in dire need of maintenance now anyway.)

    A few other reasons that jQuery is unavoidable :
    1) jQuery is by default linked in the core WordPress code. Unless deregistered/dequeued. Try to compete with this : http://en.wordpress.com/stats/
    2) Adding to 1) that most WP site owners are aware of jQuery’s presence in WP, because WP plugin requirements list jQuery as already installed by WP. Try to argue with that when promoting your bespoke JavaScript solution.
    3) I’ve worked on many commercial WP themes the past year for local commercial themes sites, and the owners of the sites are really only interested in cutting development cost and time, because the themes were going to be pirated anyway. They are not interested in code tweaked for ultimate efficiency (and beauty), at all.
    4) Companies are actually adding jQuery (whichever version that may be) as a standard to their development tools/cycle.
    5) I’m getting to here more frequently from clients that they don’t want to depend on “just me and my bespoke JS library”. Their company policy mandates that the option to hire anyone is more important, than a stranglehold by a better bespoke solution.
    6) I’m getting a lot of JavaScript projects where I have to migrate legacy JavaScript code to jQuery, Zepto, or MooTools, etc. (BTW, the word “legacy” did not originate from me.)

    • http://www.optimalworks.net/ Craig Buckler

      Thanks Robert.

      I can understand your hesitation at believing the vendors are and will always work together, but there are few competitive reasons for building a browser which is different to the others.

      Put it this way: isn’t it just as likely the jQuery team could abandon the library? There are fewer reasons to use it now older IEs are dying out. Is it better to presume jQuery will always be available and able to fix future browser inconsistencies (assuming there are some)?

      As for the other reasons:

      1. jQuery is only in WordPress templates if you put it there. Most people do — I don’t unless it’s required. In my experience, many templates are multi-megabyte monstrosities created by cut-and-paste coders; I wouldn’t cite them as a good reason to use jQuery.

      2. Does jQuery make coding quicker and easier? If you’re supporting IE6/7/8, absolutely. If you’re not, the gains are not so great. Keeping up with the latest versions and re-testing your code is a significant overhead.

      3. Why are companies paying you to migrate working legacy JavaScript code to jQuery? If it’s seriously broken, perhaps that’s fair enough — otherwise, aren’t they wasting time and money?

      My point is: do you need a generic JavaScript library when modern browsers provide consistent implementations of DOM manipulation, event handling, animation and Ajax? You might want a few three-line shortcut functions, but is 30Kb of code (280Kb uncompressed) absolutely necessary?

      If you prefer jQuery, then go for it. If you want lots of pre-written plug-ins, that’s fine. If you require a documented base for your application, jQuery may help. But all these reasons are logistical — not technical. So far, no one’s been able provide a single technical reason why jQuery (or any other library) is essential in a post-oldIE era.

      • Robert

        True. jQuery could also be abandoned.
        One of my “competitors” said that he’d rather dive into the jQuery JS code to resolve a bug. Or if jQuery was ever abandoned, to maintain it. Rather than dive into the C++ code of x number of browsers.

        The point I’was trying to make with my post is that there is (almost) no escape from jQuery anymore. That probably didn’t come across because it was inundated by my many words. (As usual.)
        I prefer to write straight JS, but more often than not it’s not allowed or asked for. For which I have already given reasons. So I use what clients want me to use : jQuery, and others.

        And you are right, I cannot think of a single technical reason to keep using jQuery over straight JS. When it comes to modern browsers. I did try to think about one or two before responding.

        I mentioned my other reason 1) in response to that the browser would still have to load and parse jQuery. jQuery is used by the WP dashboard. I didn’t mention themes. Although I’m pretty sure that it’s also loaded by the default TwentyTwelve theme.
        And you can’t really deactivate the version of jQuery which is bundled with WP. Even when you use a different version for WP themes and plugins, the WP admin back-end will still use the bundled version of jQuery. And so will the back-end of your theme. Talk about being force fed. ;)
        So I also go for jQuery at the front-end of the themes I create. (Covering my head now.)

        I’m definitely not supporting anything below IE9. I even refuse work which involves maintaining compatibility with older browsers. I’ve had it with that.

        The companies are paying me to migrate straight (what they call legacy) JS code, with various combinations of the following :
        (someone, or a group in their organization decided that) straight JS is a security risk
        straight JS is a lock-in to a small party
        straight JS is harder to maintain, and therefore brings higher cost
        jQuery, Zepto, MooTools or WHY is one of their new standards
        jQuery, Zepto, MooTools or WHY will allow them to add functionality with plugins, for just the cost of testing. (You’re hired to kill your income.)

        I’m laughing at all of their reasons, because I’m an IBM Midrange escapee. I’ve gone through similar arguments about that platform, and years ago decided to escape it. I heard : legacy, old and slow development cycle, green screens, old technology,
        But IBM Power systems are shipped with full LAMP stacks, and more. Add to that Zend’s involvement for the past umpteen years, and I do not understand this.
        In a way it’s funny to hear similar arguments now about straight JS, Sort of, because I love JavaScript. This time I’m making money of the reasons given, instead of fighting and defending them. Although sometimes it’s hard to keep my mouth shut.

      • http://www.optimalworks.net/ Craig Buckler

        Thanks Robert. It’s true that jQuery could be maintained even if it were abandoned, but remember that fixing browser issues is done in JavaScript — not C++ — that’s exactly what jQuery does.

        You’re right about WP control panels loading jQuery, but it still supports older IEs so there’s a direct benefit. If you’re creating templates for release, there’s also a reasonable reason to use jQuery because buyers will almost certainly expect it.

        I’ve never heard an argument for “straight JS being a security risk”? Bizarre. Do they understand jQuery is written in “straight JS”? Take their money and run!

      • Robert

        A security risk the say, because jQuery is used by many sites and maintained by many developers, and just straight JS is not. So security related bugs in jQuery would be caught earlier.
        This is one of the occasions that I find it hard to keep my mouth shut. Talk about being paranoid.
        Anyway I’m going off-topic here (again).

        And yes I’m taking their money. But I’m not running yet. There are too many left to make money off. :)

  • JimK

    Jquery’s power is simplifying DOM manipulation and ajax calls with far less code than plain js. Sure there can be bloat with jquery, but that’s usually due to novice excessive use of plugins. I write far less code doing some complex DOM manipulation/ajax stuff with jquery than straight js. Its a great time saver, easy to implement and happens to help with cross browser issues (unless you are using version 2.0).

    While we are on this topic, how come you all just don’t code in assembly? I mean why use java or C#, or python or ruby etc.

    • http://www.optimalworks.net/ Craig Buckler

      Agghh! Let’s crush this myth once and for all. JavaScript vs jQuery is not akin to assembly vs higher-level languages. jQuery is written in JavaScript. Native JavaScript can do everything jQuery can. However, jQuery can only perform a subset of JavaScript functionality.

      You appear to be clinging to the notion that DOM manipulation and Ajax is inconsistent. Are you still supporting IE6 and 7? If so, you’re absolutely right. If not, you may be using jQuery to smooth over inconsistencies which are no longer there!

      It’s only a time-saver because you’re used to developing with it and are probably hesitant about diving into programming without a jQuery life-jacket. I urge you to try native JavaScript and learn how the browser APIs work. At the very least, it’ll make you a more proficient jQuery developer.

  • will

    Oh you need it OK. IE 10 isn’t exactly compatible with IE9, Firefox, Chrome and Safari on <a rel=”nofollow”> tags! And apart from that, we’ve got customers using IE7 and Windows/XP who can’t afford to update because it will change their whole infrastructure.

    • http://www.optimalworks.net/ Craig Buckler

      If you’re supporting oldIEs, jQuery v1.x is useful to the point of being essential for most developers.

      As for IE10, what’s your problem with rel=”nofollow” tags? Sounds like a bizarre edge case — how does jQuery help?

  • http://www.twitter.com/theoutlander Nick Karnik

    Good article. I completely agree with eliminating the need for jQuery! If you’re supporting the latest and greatest it’s not so much of an issue.

    Perhaps the need for libraries these days is for areas like SVG vs. Canvas vs. VML where not all of them support it uniformly and each has pros and cons. I really like how OpenLayers allows rendering geometries and specifying the order of renderers to be either of the above.

  • Jonas

    I rewrote the AJAX example from the jquery.com frontpage to plain javascript. See the difference here (http://pastebin.com/rV6KqVy2).

    One thing I noticed when comparing the two are how much more self-explaining native javascript are compared to jquery. Names like onreadystatechange, open and send tells you something about what happens.

    • http://www.optimalworks.net/ Craig Buckler

      jQuery hides much of the native Ajax functionality from you. In some ways that’s good — it allows you to concentrate on the important stuff. In other ways, it’s not — developers often forget essentials such as error-checking and timeouts or fail to appreciate newer XMLHttpRequest2 features.

      A little understanding of the native JavaScript methods will help you understand jQuery better.

  • pixelBender67

    Excellent points, I find that I using jQuery less these days