I can't be the only one getting tired of sites like this making the front page. Really? It would be one thing to see someone write a legitimate article on why they think the move to JS frameworks is harmful and/or the benefits of using plain JS, and for that to make it to the front page. I'd be interested in that perspective. But this is just somebody being snide. It's the internet equivalent of the kid on The Simpsons that points and goes "ha-ha!" There's no content. We can't have a discussion around a smartass joke like this.
Reading the example code I learned enough to become interested in vanilla javascript. Although satirical in tone, I found it insightful. It lead me to question the necessity of using jQuery for every project.
I used to wonder the same thing, but after a while I've found that it already pays to include jQuery (or similar) as soon as your code reaches a complexity of "does more than one kind of thing" (roughly).
You're right. And now I feel bad that my whiny comment is the top-rated one, edging out that interesting discussion, but oh well. Hopefully I motivated people to prove me wrong. :)
Actually accepting that you had a whiny comment is what's keeping you on top, hehe. Anyways, I felt the same way, oh man another fake library that complaints about frameworks & libraries. It's alright these have to repeat from time to time, not everybody saw the last one, etc.
You're not the only one. Considering that the owner have ads on the site, gives evidence of someone who want to make a quick and easy buck from trolling the community.
Fast and lightweight, yes. But vanilla-js is certainly not cross platform ;) You see, that's actually one of the biggest problems with JS and one of the main reasons why people use things like jQuery (apart from the pretty API..).
If you're only targeting modern browsers (latest Chrome/FF/Opera/Safari, IE10), is this still true? I was under the impression the recent browsers were standards-compliant enough that you could use vanilla JS.
Of course, most developers still have to target older browsers, but for a private Web app where you know your target audience, this shouldn't be a huge issue.
There are always quirks, which I assume is what the grandparent is referring to. For example, in WebKit popstate happens on page load, in Firefox it does not. There are many such quirks. Still not worth using a DOM library that will hurt performance, though, in my opinion.
Until Microsoft either discontinues support for Windows XP or releases a modern version of IE for it, libraries like jQuery are all but necessary, in my opinion.
And what's IE10s market percentage? Less than a fraction of a fraction of a percent I bet. And with current reviews of Win8, I don't see that changing in a meaningful way for soooome time.
I think you missed the announcement where Microsoft is going to do a silent update of IE10 to consumer PC's. IE9 usage will drop to the low single digits within a year and IE10 will take its place as the leading IE browser.
How's this going to work for corporate installs? As much as I love the idea of big companies being forced forward, I have the nagging feeling that Microsoft will include a get-out-of-jail-free card for them.
(Speaking as a medium-sized corporation user stuck on Snow Leopard. :] )
The "force" upgrade everyone is talking about is an optional thing. You will be able to go into the settings and turn that off (specifically for corporate use).
IE9 doesn't run on Windows XP. IE10 won't run on Windows Vista. So it's safe to say that even with silent updates (which still won't automatically run on corporate machines with corporate IT policies that control the updates), IE8 and IE9 usage won't rapidly drop into low single digits.
IE8 will probably be more persistent than IE9. I think a lot of corporations are still on XP. Mine is, for example. When companies finally make the jump to Win7, I think they'll move pretty quickly to IE10, so as not to be too far behind. After all, we should expect IE11 next year.
As a note, at my company last year the xp images JUST got IE7. And last week, as the first group of people, our group got upgraded to Win 7+IE8. Major corporations are slooooow at updates.
I'm just happy its happening at all, I know people at banks that have IE6 still.
You're right. That was fairly nonsenical. Not sure what I meant, perhaps I read your comment as referring to requests.
Either way, long-term caching of such shims means the bandwidth to load polyfills only has to be expended once per client. And an extra Mb of bandwidth once per year is a pretty reasonable thing to do for particularly older browsers if it makes your development more sane.
This enumeration is done the wrong way. You enumerate over a DOM node list which looks like an array, which includes enumerable properties like "length". This means that the variable "p" at some point will be "length" and "length".innerHTML = "..." will produce an error.
The proper way is:
for( var i=0, ps=document.getElementsByTagName('p'), len=ps.length; i < len; i++) {ps[i].innerHTML = 'Hello.';}
I'm a JS noob, but I though 'length' was not enumerable (i.e. its 'enumerable' property is set to 'false').
Edit: I think I missed what you said. You're saying it's "like" and array, but unlike arrays its `length` is enumerable. I'll leave my comment so other skeptics can benefit :)
That's ES3. You have no reason to choose that way anymore - ES5 loops work everywhere current, can be polyfilled into IE8, and don't require any boilerplate stuff.
var paragraphs = document.getElementsByTagName('p');
document.getElementsByTagName returns a DOM Node List and it does not have forEach method according to the DOM spec. DOm Nodes, Elements and Node Lists and Node Maps do not follow the javascript spec (ECMAScript) hence do not share methdos and properties. A Dom Node List does not have the methods of the javascript array. That is because DOM Node List does not inherit from the Array.prototype, because it is not javascript - it has its own spec that exactly determines what methods and properties it should have. The implementation in the browser happens to be accessible through javascript but that does not mean that the DOM is part of javascript. That is why wrapper libraries like jQuery or other abstractions are necessary to make the DOM much more accessible from a JS perspective. BTW that is why many people confuse DOM with javascript and then get frustrated which is understandable.
Except #forEach is a method of Array, and getElementsByTagName does not return an Array but a NodeList. Which doesn't have any of Array's methods (it has a length, it can be indexed, and it has an alternative indexation method - #item — but it's not an array at all)
Also in the native version, you know you're only doing the work required. The jquery one will be doing a lot of extra useless inefficient grunt work to achieve nothing. Making it incredibly slow in comparison.
Premature optimization, and all that. It is trivial to get raw dom nodes out of jQuery, so you can easily use jQuery to begin with and replace any code with the full DOM API calls should it every become a performance issue.
This discussion is a bit like how assembly programmers used to defend not moving to a high level language long after the performance benefits were not worth it any more.
> This discussion is a bit like how assembly programmers used to defend not moving to a high level language long after the performance benefits were not worth it any more.
But we're not at that point in the web yet. The performance benefits are worth it. Just try out JQuery Mobile if you want to see what wasted CPU cycles can do.
It may be worth it for specific use cases, just like there are certainly still specific use cases where assembly shines.
The point is we're well past the point where grasping for the asm-equivalent from the start should be the default unless you happen to specifically target one of those niches.
It depends on what you're trying to do. Mostly, I try to write code that displays the same in every possible browser without special-casing or using confusing idioms. CPU cycles are cheap. A webpage that loads a little slow is a possible lost sale. A webpage that fails to load is a definite lost sale.
> It is trivial to get raw dom nodes out of jQuery, so you can easily use jQuery to begin with and replace any code with the full DOM API calls should it every become a performance issue.
That's still going to be a lot of work if the performance issues turn out to be many separate jQuery calls spread all over your code, which is not unlikely.
"Useless" is subjective, but the jQuery object does a lot of extra work above the vanilla example.
$ isn't just a syntax layer on top of querySelectorAll. When you do $('p'), it first queries the DOM for everything that matches that selector, then it creates new jQuery objects to wrap each of the returned nodes as well as creating a jQuery object to contain them.
If all you're doing is setting the innerHTML of these objects, it's a non-trivial overhead.
It creates just one jQuery object to wrap the entire array of DOM nodes. Afterwards, .html() is essentially innerHTML [1], provided jQuery can use it directly (otherwise it has to create DOM nodes by itself).
I am a c developer, now I want to learn jQuery , but its syntax seems so weird to me, Vanilla JS looks more comfortable to me , one questions, does it supported by webkit?
I'm sorry. I don't know if you're joking or are serious. But if you're a C programmer and have no experience with JS I guess it must be really easy to be fooled by this "joke".
Some JS people (the ones usually with a long beard) hate how kids use frameworks like jQuery and this site is an attempt at telling them "The vanilla JS, i.e. the standard language that all browsers use and your cool jQuery leverage under the hood, is quite capable these days. Use it". They are not quite right, but aren't quite wrong either (IMO). You'll be a dreadful JS programmer if you only know jQuery. JS is sooo different from C (and Java) that if you don't know the core language everything you'll do will be wrong. For starter: there's no block scope. Only function scope.
Every JS programmer should read "JavaScript: The Good Parts" by Douglas Crockford cover to cover - before learning jQuery.
I want to learn something about jQuery,because recently I need to develop an application which use webkit. It has a feature that need to highlight some special words. After search in the internet, I found the jQuery can 'easily' do that. But the syntax of jQuery make me headache, then I happened to see this article.
Thank you very much , I am very appreciate for your advice:)
This site could actually be made useful if the little area where you check which "features" you want to include that "generated" the download file actually caused cross-platform, native JavaScript examples of those bits of functionality to be included in a real downloadable file.
If you really think more people should be using plain vanilla JavaScript (and in a lot of places, I think this is actually true and even when a framework is needed, it's good to have the underlying skill) then the way to get them to do that is to educate them on it, not patronize.
Raw Javascript is simply not an option. The API is awful, default types are not powerful enough and cross-platform consistency is a joke. For every decently sized project you start in JS you have to reinvent a thousand wheels to even get rolling, so you better just leverage a framework.
Recently, I was interviewing a front-end developer candidate and I gave them a simple JavaScript problem. The sad thing was, they didn't recognize `document.getElementById()` and didn't know any of the parameters to `addEventListener()`.
We finished the exercise assuming the example used jQuery instead.
I agree. I think it's important to know Javascript as a language well, but there are very few cases when you'd be using Javascript without some abstraction from the DOM.
maybe I'm mistaken, but I think this is more of "jquery programmer" problem. jQ really abstracts away from the nitty gritty of the dom api and also for any beginner / intermediate frontend guys the source is not very readable. In comparison dojo for example, requires you know what you're doing and also to have pretty extensive knowledge about js, the dom, etc. Also, in my opinion, its source code is very clean in comparison.
Was anyone else surprised by the performance penalty of jQuery? Over 400x hit for getElementsByTagName! I'm curious whether this is more due to cross browser checks or determining the what type of selector was used. To the source!
> Was anyone else surprised by the performance penalty of jQuery? Over 400x hit for getElementsByTagName!
Not really. Just replacing document.getElementsByTagName by document.querySelectorAll (the native, browser-implemented version of what jQuery does) will generate a 150-200x perf hit depending on the browser.
The reason for that is twofold: first, getElementsByTagName doesn't have to parse the selector, figure out what is asked for, and potentially fall back on explicit JS implementation (jQuery supports non-native selectors. In fact, I believe you can implement your own selectors). But the parsing overhead should be minor in this precise case.
Second, the real reason for the difference, getElementsByTagName cheats something fierce: it doesn't return an Array like everybody else, it returns a NodeList. And the nodelist is lazy, it won't do anything before it needs to. Essentially, just calling document.getElementsByTagName is the same as calling an empty function. If you serialize the nodelist to an array (using Array.prototype.slice.call), bam 150~200x perf hit.
I suspect the benchmark is flawed, and charging jQuery for one-time penalties for every function. i.e., if you make a page that has nothing but a getElementById call, vs. loading jQuery and executing the query on the DOM, it's obviously going to be a lot slower. Even if that's not the case, "fast enough" is fast enough...and jQuery has proven itself to be fast enough for a lot of stuff. And, most developers working in JavaScript and building their own helper libraries and such are extremely likely to make worse libraries than jQuery. So, it's probably smarter to use a library that's getting a lot of vetting by really smart people. Whether it's jQuery or something else, I'm not gonna go back to hand-written JavaScript (I'm in the midst of converting an app to use jQuery from handwritten functions, and the new version is either faster or similarly fast, and maintenance of the frontend is getting vastly simpler with every element that gets converted from the handwritten functions to jQuery+Bootstrap...hell, sometimes, I'm able to just use markup with no JavaScript on the page at all...and that's like magic).
Question: is the 'Speed Comparison' for real? I find it really, really hard to believe. Surely jQuery & co. revert to native implementations (if they exists, as they do in all modern browsers) for things like `document.getElementById` and don't iterate over the whole DOM.
Depends what you mean by "for real". The document.getElementsByTagName comparison is bullshit: gEBTN is lazy, just calling it basically doesn't do any work, it just allocates a NodeList object and returns.
If you serialize the nodelist to an array or use document.querySelector instead (it returns an array) you get ~3x between the native version and the slowest libraries, not 400x.
Yeah, Sizzle will grab an element using `document.getElementById()` but only after checking the nodeType of the context, ensuring the selector is a string and running the selector through a regular expression.
I just looked at the latest jquery and its each statement does not do a native fallback, which really surprised me. Also you have to keep in mind that a simple $('a.active').each(someFunc), has to run through the a lot of jq luggage, plus the initial http fetch of the library (which has come under criticism for its size).
I love pure JavaScript. jQuery is overrated and most libraries are only good for one thing or the other, nothing can replace the joy and performance of Vanilla JS!
jQuery is kind of a big download for mobile, so I often skip it for small tasks.
What gets me is when people include jQuery and then further bog things down by loading a lot of plug-ins to do things that could easily be accomplished by adding a few lines of code of their own. Even if you do need and include jQuery, it doesn't mean you have to use it for every piece of javascript in your app.
Many times, a plug-in will do a lot more than you need it to do. If your primary goal is to just get rid of the 300sm delay translating tap events to click events, you don't need a library for full gesture support. You need half a dozen lines to listen for touch events.
If you just need to add some client-side persistence for a few basic things in LocalStorage, you probably don't need a plug-in with a complex query syntax.
Cannibalize a library if you need to and pull out the bits you need. You don't have to include the whole kitchen sink.
> jQuery is kind of a big download for mobile, so I often skip it for small tasks.
That's what Zepto[0] is for: jQuery's API, 20% of the size (although it drops some features, e.g. $(selector) is pretty directly proxied to document.querySelectorAll, so $('> .foo') works in jQuery but blows up in Zepto)
Ah, last I looked at Zepto, it's support for non-webkit browsers was pretty lacking. It's good to see they're making strides on the cross-platform comparability front. The supported browsers list looks pretty good now.
I'm surprised by the number of comments like this.
jQuery has to parse the selector and figure out that it's of the form "#id". This requires running a regular expression. A lot more is happening.
The whole jQuery call from start to finish takes 2.85 microseconds, in what is presumably a real benchmark, but microbenchmarks like this are hard to interpret and basically meaningless. But yes, if your app needs to do a burst of 350,000 jQuery calls in a tight loop and you are bummed that the whole thing takes a full second, you should then optimize using document.getElementById.
> I'm surprised by the number of comments like this.
The sentiment is borne out by the facts when you dig a little deeper. Just calling document.getElementById without using the return value does not actually dig into the DOM and find the element according to this comment: http://news.ycombinator.com/item?id=4436438
> if your app needs to do a burst of 350,000 jQuery calls in a tight loop and you are bummed that the whole thing takes a full second, you should then optimize using document.getElementById
Seems like you might have some other optimization work to do at that point :)