Hacker News new | ask | show | jobs
by ashray 5038 days ago
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..).

That cross platform bit is the weakest link sigh.

3 comments

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.

What about IE8? That's still well above 10% I think.
Depending on where you look, it's at about 14%.

http://gs.statcounter.com/#browser_version-ww-daily-20120820...

Aren't the polyfills pretty good nowadays?
Yes, but using all of them needed for full HTML5 support in, say, IE6, probably takes up more bandwidth than downloading a new browser.
It doesn't take up any more bandwidth if you're properly concatenating your JS.
Uh, no. I think you misunderstand me.
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.

Most people using IE6 are doing so because they can't download a new browser e.g. ActiveX support or lockdown corporate machine.
jQuery API is not pretty
I'll take

  $('p').text('Hello.')
over

  for (var p in document.getElementsByTagName('p')) { p.innerHTML = 'Hello.'; }
any day!
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 :)

Edit2: This is what I was referring to (read the 'Note' at the right side): http://bonsaiden.github.com/JavaScript-Garden/#object.forinl...

Looks like this is correct:

paras = document.getElementsByTagName('p') for (var para in paras) { console.log(para)} 0 1 ... 9 10 length item

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');

paragraphs.forEach(function(paragraph){paragraph.innerHTML = 'Hello.';})

This will not work - Check my solution below :)

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)
You're right. I wasn't sure earlier, as I was typing on a phone with no JS console.

but never mind:

Array.forEach.call(paragraphs, function(paragraph){paragraph.innerHTML = 'Hello.';})

will work fine.

Ah, thanks for the correction! I just wrote it out from memory, and it's been a while since I used Vanilla-JS DOM selectors ;)
Try this in a browser. On Webkit at least is also returns length and item:

for (var p in document.getElementsByTagName('p')) {console.log(p);}

The jquery version is easier to write, and less prone to error, but in the native version it's much more clear what's actually going on.
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 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.

The jquery one will be doing a lot of extra useless inefficient grunt work

Such as?

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

>but in the native version it's much more clear what's actually going on.

Yes, but it's also more probable that it won't go on at all (due to browser incompatibilities and such).

did you ever try to debug your pretty jquery karate?

ps. second example is not valid, in Vanilla JS you do it like this:

  document.getElementsByTagName('p').filter(function(el) {
    el.innerHTML = 'Hello.';
  });
The right way is this :)

Array.prototype.forEach.call(document.getElementsByTagName('p'), function(el) { el.innerHTML = 'Hello.'; });

I like how the end of that statement contains both a winking crooked-smile smiley next to black-eyed frown smiley.
Nope:

TypeError: document.getElementsByTagName("p").filter is not a function

Because you don't get an array, only something array-like.

And this discussion over how to write a trivial loop is why I stay far away from vanilla js unless performance absolutely forces me to optimize.
This is why I program with a code editor / interactive console that tells me these things as I'm typing :-)
I'll take $(node).remove() over node.parentNode.removeChild(node) any day.
innerHTML is an easy one, try setting an attribute -- you have to create a new attribute node, set its value and then add that to the element..
> you have to create a new attribute node, set its value and then add that to the element..

Erm... no you don't: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-F68F082

You should set the node property instead (e.g. standard textContent or innerText). It will work everywhere.
setAttribute()?
IE8 =(
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.

there's no block scope. Only function scope.

There is global scope as well, and it's (unfortunately in most cases) the default.

Also there is block scope. let { ... }
AFAIK, let is a Mozilla only feature.
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:)
Look at other libraries. I cant beat the MooTools drum loud enough.
Compared to the dom api, it is very pretty.