Categories
Rants

Is the current tab active?

Reading Time: 4 minutes

Today I ran into an interesting problem. Interesting because it’s one of those very straightforward, deceptively simple questions, that after a fair amount of digging, does not appear to have a definite answer (though I would love to be wrong!).

The problem was to determine if the current tab is active. Yes, as simple as that.

Categories
Rants Thoughts

The failed promise of Web Components

Reading Time: 4 minutes

Web Components had so much potential to empower HTML to do more, and make web development more accessible to non-programmers and easier for programmers. Remember how exciting it was every time we got new shiny HTML elements that actually do stuff? Remember how exciting it was to be able to do sliders, color pickers, dialogs, disclosure widgets straight in the HTML, without having to include any widget libraries?

The promise of Web Components was that we’d get this convenience, but for a much wider range of HTML elements, developed much faster, as nobody needs to wait for the full spec + implementation process. We’d just include a script, and boom, we have more elements at our disposal!

Or, that was the idea. Somewhere along the way, the space got flooded by JS frameworks aficionados, who revel in complex APIs, overengineered build processes and dependency graphs that look like the roots of a banyan tree.

This is what the roots of a Banyan tree look like. Photo by David Stanley on Flickr (CC-BY).
Categories
Rants

Today’s Javascript, from an outsider’s perspective

Reading Time: 3 minutes

Today I tried to help a friend who is a great computer scientist, but not a JS person use a JS module he found on Github. Since for the past 6 years my day job is doing usability research & teaching at MIT, I couldn’t help but cringe at the slog that this was. Lo and behold, a pile of unnecessary error conditions, cryptic errors, and lack of proper feedback. And I don’t feel I did a good job communicating the frustration he went through in the one hour or so until he gave up.

Categories
Rants Thoughts

On the blindness of blind reviews

Reading Time: 2 minutesOver the last couple of years, blind reviews have been popularized as the ultimate method for fair talk selection in industry conferences. While I don’t really submit proposals myself, I have served several times on the other side of the process, doing speaker selection in conference committees, and the more data points I collect, the more convinced I become that the blind selection process is fundamentally flawed.

Blind reviews come from the world of academia. However, in academic conferences, you do not judge a talk by a 1-2 paragraph abstract, but by a 10+ page paper, so there’s way more to judge by. In addition, in academia the content of the research matters infinitely more than the quality of a talk. In industry conferences, selection committees in blind reviews have both way less data to use, and a much harder task, as they need to balance several factors (content, speaker skill, talk quality etc). It’s no surprise that the results end up being even more of a gamble.

Blind reviews result in conservative talk selection. More often than not, I remember me and my fellow committee members saying “Damn, this talk could be great with the right presenter, but that’s rare” and giving it a poor or average score. Few topics can make good talks regardless of the presenters. Therefore, when there is little information on the speaker in the initial selection round, talk selection ends up being conservative, rejecting more challenging topics that need a skilled speaker to shine and sticking to safer choices.

One of my most successful talks ever was “The humble border-radius” which was shortlisted for a .net award for Conference Talk of The Year 2014. It would never have passed any blind review. There is no committee in their right mind that would have accepted a 45 minute talk about …border-radius. The conferences I presented it at invited me as a speaker, carte blanche, and trusted me to present on whatever I felt like. Judging by the reviews, they were not disappointed.

In addition, all too many times I’ve seen great speakers get poor scores in blind reviews, not because their talks were not good, but because writing good abstracts is an entirely separate skill. Blind reviews remove anything that could cause bias, but they do so by striping all personality away from a proposal. In addition, a good abstract for a blind review is not necessarily a good abstract in general. For example, blind reviews penalize more mysterious/teasy abstracts and tend to be skewed towards overly detailed ones, since it’s the only data the committee gets for these talks (bonus points here for CfS that have a separate field for more details to conf organizers).

“But what about newcomers to the conference circuit? What about bias elimination?” one might ask. Both very valid concerns. I’m not saying any kind of anonymization is a bad idea. I’m saying that in their present form in industry conferences, blind reviews are flawed. For example, an initial round of blind reviews to pick good talks, without rejecting any at that stage, would probably solve these issues, without suffering from the flaws mentioned above.

Disclaimer: I do recognize that most people in these committees are doing their best to select fairly, and putting many hours of (usually volunteer) work in it. I’m not criticizing them, I’m criticizing the process. And yes, I recognize that it’s a process that has come out of very good intentions (eliminating bias). However, good intentions are not a guarantee for infallibility.

Categories
Rants

jQuery considered harmful

Reading Time: 4 minutesHeh, I always wanted to do one of those “X considered harmful” posts*. 😀

Before I start, let me say that I think jQuery has helped tremendously to move the Web forward. It gave developers power to do things that were previously unthinkable, and pushed the browser manufacturers to implement these things natively (without jQuery we probably wouldn’t have document.querySelectorAll now). And jQuery is still needed for those that cannot depend on the goodies we have today and have to support relics of the past like IE8 or worse.

However, as much as I feel for these poor souls, they are the minority. There are tons of developers that don’t need to support old browsers with a tiny market share. And let’s not forget those who aren’t even Web professionals: Students and researchers not only don’t need to support old browsers, but can often get by just supporting a single browser! You would expect that everyone in academia would be having tons of fun using all the modern goodies of the Open Web Platform, right? And yet, I haven’t seen jQuery being so prominent anywhere else as much as it is in academia. Why? Because this is what they know, and they really don’t have the time or interest to follow the news on the Open Web Platform. They don’t know what they need jQuery for, so they just use jQuery anyway. However, being able to do these things natively now is not the only reason I’d rather avoid jQuery.

Yes, you probably don’t really need it…

I’m certainly not the first one to point out how much of jQuery usage is about things you can do natively, so I won’t spend time repeating what others have written. Just visit the following and dive in:

I will also not spend time talking about file size or how much faster native methods are. These have been talked about before. Today, I want to make a point that is not frequently talked about…

…but that’s not even the biggest reason not to use it today

To avoid extending the native element prototypes, jQuery uses its own wrapper objects. Extending native objects in the past was a huge no-no, not only due to potential collisions, but also due to memory leaks in old IE. So, what is returned when you run $("div") is not a reference to an element, or a NodeList, it’s a jQuery object. This means that a jQuery object has completely different methods available to it than a reference to a DOM element, an array with elements or any type of NodeList. However, these native objects come up all the time in real code — as much as jQuery tries to abstract them away, you always have to deal with them, even if it’s just wrapping them in $(). For example, the context when a callback is called via jQuery’s .bind() method is a reference to an HTML element, not a jQuery collection. Not to mention that often you use code from multiple sources — some of them assume jQuery, some don’t. Therefore, you always end up with code that mixes jQuery objects, native elements and NodeLists. And this is where the hell begins.

If the developer has followed a naming convention for which variables contain jQuery objects (prepending the variable names with a dollar sign is the common one I believe) and which contain native elements, this is less of a problem (humans often end up forgetting to follow such conventions, but let’s assume a perfect world here). However, in most cases no such convention is followed, which results in the code being incredibly hard to understand by anyone unfamiliar with it. Every edit entails a lot of trial and error now (“Oh, it’s not a jQuery object, I have to wrap it with $()!” or “Oh, it’s not an element, I have to use [0] to get an element!”). To avoid such confusion, developers making edits often end up wrapping anything in $() defensively, so throughout the code, the same variable will have gone through $() multiple times. For the same reason, it also becomes especially hard to refactor jQuery out of said code. You are essentially locked in.

Even if naming conventions have been followed, you can’t just deal only with jQuery objects. You often need to use a native DOM method or call a function from a script that doesn’t depend on jQuery. Soon, conversions to and from jQuery objects are all over the place, cluttering your code.

In addition, when you add code to said codebase, you usually end up wrapping every element or nodelist reference with $() as well, because you don’t know what input you’re getting. So, not only you’re locked in, but all future code you write for the same codebase is also locked in.

Get any random script with a jQuery dependency that you didn’t write yourself and try to refactor it so that it doesn’t need jQuery. I dare you. You will see that your main issue will not be how to convert the functionality to use native APIs, but understanding what the hell is going on.

A pragmatic path to JS nudity

Sure, many libraries today require jQuery, and like I recently tweeted, avoiding it entirely can feel like you’re some sort of digital vegan. However, this doesn’t mean you have to use it yourself. Libraries can always be replaced in the future, when good non-jQuery alternatives become available.

Also, most libraries are written in such a way that they do not require the $ variable to be aliased to jQuery. Just call jQuery.noConflict() to reclaim the $ variable and be able to assign it to whatever you see fit. For example, I often define these helper functions, inspired from the Command Line API:

// Returns first element that matches CSS selector {expr}.
// Querying can optionally be restricted to {container}’s descendants
function $(expr, container) {
	return typeof expr === "string"? (container || document).querySelector(expr) : expr || null;
}

// Returns all elements that match CSS selector {expr} as an array.
// Querying can optionally be restricted to {container}’s descendants
function $$(expr, container) {
	return [].slice.call((container || document).querySelectorAll(expr));
}

In addition, I think that having to type jQuery instead of $ every time you use it somehow makes you think twice about superfluously using it without really needing to, but I could be wrong 🙂

Also, if you actually like the jQuery API, but want to avoid the bloat, consider using Zepto.

* I thought it was brutally obvious that the title was tongue-in-cheek, but hey, it’s the Internet, and nothing is obvious. So there: The title is tongue-in-cheek and I’m very well aware of Eric’s classic essay against such titles.

Categories
Rants

Why tabs are clearly superior

Reading Time: 4 minutesIf you follow me on twitter or have heard one of my talks you’ll probably know I despise spaces for indentation with a passion. However, I’ve never gone into the details of my opinion on stage, and twitter isn’t really the right medium for advocacy. I always wanted to write a blog post about my take on this old debate, so here it is.

Tabs take up less space

Yes, this might be an insignificant difference after gzipping and a nonexistent one after minification. But it means you need these processes to keep your code size reasonable. You depend on them, for no reason. Comments for example are useful, and it’s worth having them even if you knew you couldn’t minify or gzip your code. Tabs could do the same thing as spaces, so you’re just bloating your code for no reason.

Tabs can be personalized

The width of a tab character can be adjusted per editor. This is not a disadvantage of tabs as commonly evangelized, but a major advantage. People can view your code in the way they feel comfortable with, not in the way *you* prefer. Tabs decouple the code’s presentation from its logic, just like CSS decouples presentation from HTML. They give more power to the reader rather than letting the author control everything. Basically, using spaces is like saying “I don’t give a rat’s ass about how you feel more comfortable reading code. I will force you to use my preferences because it’s my code”.

Tabs are better for collaboration

Personalization is incredibly valuable when a team is collaborating, as different coders can have different opinions. Some coders prefer their indents to be 2 spaces wide, some coders prefer them to be 4 spaces wide. Rather than manually or automatically converting the code post-pull, and then back pre-commit, it would be adjusted automatically, depending on the editor’s tab-width setting, so every coder could start editing right away, with their favorite type of indent.

You don’t depend on certain tools

When using spaces, you depend on your editor to hide the fact that an indent is actually N characters instead of one. You depend on your editor to insert N spaces every time you press the Tab key and to delete N characters every time you press backspace or delete near an indent. When you have to use something that’s not your editor (for example when writing a snippet of code on a webapp that embeds something like codemirror) you will have to face the ugliness of your decision. Especially with codemirror, everyone else will have to face the ugliness of spaces too, as it converts tabs to spaces 🙁

Tabs are easy to select

Assume for some reason you want to select all indents and double them or convert them to spaces. This is very easy with tabs, because that’s their sole meaning. Tabs were invented for this sort of thing. Spaces on the other hand, have many meanings, so you can’t just find & replace space characters. And how do we usually call the practice of using things for a different purpose than they were made for? Yup, that’s right, using spaces for indentation is a hack.

Code indented with tabs is easier to copy & paste

As pointed out by Norbert Süle in the comments, when you copy and paste code that’s indented with spaces, you have to manually adjust the indentation afterwards, unless the other person also happens to prefer the same width indents as you. With tabs, there is no such issue, as it’s always tabs so it will fit in with your (tabbed) code seamlessly. The world would be a better place if everyone used tabs.

But what about the web? Tabs are super wide there!

This used to be a big problem, and even the enlightened coders that prefer tabs usually convert them to spaces before posting code online. However, CSS3 solves this problem, with the tab-size property. It’s supported by Opera, Firefox and very soon by WebKit too. It also degrades gracefully: The code is less pretty, but still perfectly readable.

Are spaces always evil?

Spaces are the best choice for aligning, rather than indenting. For example, in the following code snippet:

var x = 10,
    y = 0;

you need 4 spaces to make the variables line up. If you used tabs, they would only line up when the tab width is 4 and the formatting would look messed up in every other case. However, if this code snippet was also indented, the indents could (and should) still be tabs.

Another example is aligning CSS3 properties with different vendor prefixes. The indent should be done with tabs, but the aligning with spaces, like so:

div {
	-webkit-transition: 1s;
	   -moz-transition: 1s;
	    -ms-transition: 1s;
	     -o-transition: 1s;
	        transition: 1s;
}

It’s just a pointless detail, are you seriously that obsessed?

Um, ok I am exaggerating a bit when I say how spaces suck. I do think they suck, although I admit the world has much bigger problems than coders who use spaces for indentation.

For example, coders that don’t name their variables properly. Or the ones that prefer Emacs over Vim 😉

Further reading

Update: More reasons from commenters
 
Thanks to Oli  for his proofreading!

Update: More reasons from commenters

  1. Tabs reduce typing effort (Yes, editors will insert groups of spaces automatically when you press tab, but cursor movement and deletions must be done one at a time).
  2. Tabs make typing consistent – inserting/deleting/moving past an indent is always a single keypress. With spaces, one keypress creates an indent, but then you need to press delete an *indeterminate number of times* to remove the indent. That means I have to watch what I’m doing and press delete until my cursor lines up with the previous line, or (3) occurs.
  3. Tabs are indivisible. With spaces it is easy to end up on a non-tab column, and then you have either messy code or waste time tidying up the indentation. Tabs eliminate this problem by “snapping” code to the correct indentation column automatically.
Categories
Rants

What we still can’t do client-side

Reading Time: 3 minutesWith the rise of all these APIs and the browser race to implement them, you’d think that currently we can do pretty much everything in JavaScript and even if we currently can’t due to browser support issues, we will once the specs are implemented. Unfortunately, that’s not true. There are still things we can’t do, and there’s no specification to address them at the time of this writing and no way to do them with the APIs we already have (or if there is a way, it’s unreasonably complicated).

We can’t do templating across pages

Before rushing to tell me “no, we can”, keep reading. I mean have different files and re-use them accross different pages. For example, a header and a footer. If our project is entirely client-side, we have to repeat them manually on every page. Of course, we can always use (i)frames, but that solution is worse than the problem it solves. There should be a simple way to inject HTML from another file, like server-side includes, but client-side. without using JavaScript at all, this is a task that belongs to HTML (with JS we can always use XHR to do it but…). The browser would then be able to cache these static parts, with significant speed improvements on subsequent page loads.

Update: The Web Components family of specs sort of helps with this, but still requires a lot of DIY and Mozilla is against HTML imports and will not implement them, which is one main component of this.

We can’t do localization

At least not in a sane, standard way. Client-side localization is a big PITA. There should be an API for this. That would have the added advantage that browsers could pick it up and offer a UI for it. I can’t count the number of times I’ve thought a website didn’t have an English version just because their UI was so bad I couldn’t find the switcher. Google Chrome often detects a website language and offers to translate it, if such an API existed we could offer properly translated versions of the website in a manner detectable by the browser.

Update: We have the ECMAScript Globalization API, although it looks far from ideal at the moment.

We can’t do screen capture

And not just of the screen, but we can’t even capture an element on the page and draw it on a canvas unless we use huge libraries that basically try to emulate a browser or SVG foreignObject which has its own share of issues. We should have a Screen Capture API, or at the very least, a way to draw DOM nodes on canvas. Yes, there are privacy concerns that need to be taken care of, but this is so tremendously useful that it’s worth the time needed to go intro researching those.

We can’t get POST parameters and HTTP headers

There’s absolutely NO way to get the POST parameters or the HTTP response headers that the current page was sent with. You can get the GET parameters through the location object, but no way to get POST parameters. This makes it very hard to make client-side applications that accept input from 3rd party websites when that input is too long to be on the URL (as is the case of dabblet for example).

We can’t make peer to peer connections

There is absolutely no way to connect to another client running our web app (to play a game for example), without an intermediate server.

Update: There’s RTCPeerConnection in WebRTC, though the API is pretty horrible.

_________

Anything else we still can’t do and we still don’t have an API to do so in the future? Say it in the comments!

Or, if I’m mistaken about one of the above and there is actually an active spec to address it, please point me to it!

Why would you want to do these things client-side?!

Everything that helps take load away from the server is good. The client is always one machine, everything on the server may end up running thousands of times per second if the web app succeeds, making the app slow and/or costly to run. I strongly believe in lean servers. Servers should only do things that architecturally need a server (e.g. centralized data storage), everything else is the client’s job. Almost everything that we use native apps for, should (and eventually will) be doable by JavaScript.

Categories
Rants

On CSS preprocessors

Reading Time: 4 minutesLately there has been a rise in the usage of CSS preprocessors such as LESS and SASS, which makes sense given the simultaneous increase of CSS3 usage. I’ve frequently argued with fellow front-end web developers about whether they should be used or not and I decided to finally put my thoughts in writing.

To start, I can fully understand the advantage of using such preprocessors over vanilla CSS3. I hate listing all the vendor prefixes, and not being able to use variables, mixins or nesting just like the next web developer. All this syntactic sugar can simplify your workflow by a great deal and make writing CSS3 incredibly fun. However, I still refrain from using them, and I’ll explain why below.

Categories
Personal Rants

Yet another redesign

Reading Time: < 1 minuteI had grown sick of my previous blog style and its various bugs (since it was put together in just a few hours), so I decided to make a new, more minimalistic one. Best viewed in browsers that support CSS gradients, like Firefox, Safari and Chrome. I also finally got around to making a logo for myself, although I’m not sure I’ll keep it. I also switched to HTML5, using Toolbox as a base.

I want to make a few more changes, but I have to go to sleep sometime :p

I also started using DISQUS for the blog comments. I like it when a blog I read has it (since it offers a few features I find convenient, like comment editing for instance), so I wanted to offer it to my readers too. It’s a shame that in some of their buttons they haven’t added the standard CSS3 border-radius declarations, but only the prefixed proprietary ones, so they’re square in Opera (and probably IE9). I’m fed up with seeing this in websites, TOPSY‘s widget also does it. However, their carelessness will backfire soon, when browsers stop supporting the prefixed versions *evil grin*

Categories
Rants Thoughts

“Wow, Mona Lisa with pure CSS!”

Reading Time: 2 minutesThere has been a recent flood of CSS experiments that utilize CSS3 features to convert some meaningless markup to spectacular pictures. It all started when David Desandro used CSS3 to draw the Opera logo. This seemed to inspire lots of other folks who created similar demos:

I can certainly share their enthusiasm and I am also amazed by their results. Besides that, I think that pushing CSS3 to the edge like that, helps us understand the spec better, which leads us to find and file browser bugs or write comments regarding the spec itself. Filing bugs is crucial at this stage, with all browser vendors gradually adding experimental –and frequently buggy– CSS3 support to their products. Also, don’t get me wrong: I can easily see the benefits of reducing the number of images in a web application interface (far quicker/easier modifications, less HTTP requests and most of the time, less bandwidth).

However, I’m afraid we’re losing sight of the big picture. These aren’t demos that are or will ever be legitimate CSS use cases. Even after universal CSS3 browser support is achieved, they would (and should) still be considered “hacks”. Almost all the arguments pro their usage also apply to more suitable ways of including images in web applications:

  • Fewer HTTP requests: Same with any kind of embedded image (data URIs, inline SVG and so on)
  • Scalable: Same with SVG and symbols embedded in custom fonts
  • Easier to modify: Same with SVG
  • Less bandwidth (in some cases): Same with SVG (and it can be cached too, when not inline)
And apart from these, these illustrations require non-semantic crap to be included in the markup which, besides issues of theoretical purity, makes it harder for other people to use them.
As for the graceful degradation argument, yes, this does only apply to CSS “images”. But in this case, is it really an advantage? I seriously doubt it. People won’t notice rounded corners if they’re missing from an interface, but they’re definitely going to notice a blocky Opera logo. And they’re not used in thinking that their browser has something to do with how an image renders, so they’ll just blame the website.

CSS is supposed to enhance the presentation of a document or interface, not to be (ab)used for the creation of illustrations from scratch. It’s supposed to separate presentation from structure, not generate stuff. There are other technologies that are far more suitable for this (*cough*SVG*cough*). I think we should use our energy and creativity to make CSS3 demos that people will actually use in the future when all this is fully supported, not stuff doomed to be eternally considered hackery.

“Where should we draw the line?” one might ask. For example, is a Pure CSS analog clock a CSS abuse case? Or even my own CSS iPhone keyboard? Now that’s a good question! A rule of thumb seems to be “if it inherently (=not due to browser support issues) involves a bunch of empty (or with meaningless content) HTML elements, then that’s a bad sign” but that might be overly strict. What’s your take on it?

Disclaimer: Yes, I’m fully aware that most of the time, such experiments are created just for fun by their (very talented) authors, which are perfectly aware of all the things mentioned above. However, I’ve also grown tired of reading comments by people that seem to to think that “This is the future of the web!”. Let’s hope it’s not.