Saturday, 15 September 2012

JS/HTML/CSS: A braindump from a backend guy

It's a wonderful sunny Saturday outside yet I'm here bloging about web development. I should see a doctor, but in the meantime please suffer my brain dump about things browser related.

I'm not really a front end developer, in the sense that I have very poor graphic design skills, that my knowledge of Javascript and CSS is limited. However over the time I had my fair bit of front end development, more recently here, not counting the things I do for fun, so yeah, I don't have expert level knowledge about all of this, but I feel I have enough experience to broadly think about some general guidelines about what should be fed to the browsers. So the goal of this post is not to dictate what I think is right, but rather to put some ideas on the table and calling for critics and alternative and/or improvement suggestion. So if you're a JS Ninja, or a CSS old-master, please be indulgent, and share your art in the comment.

Ok let's get started with the general page structure. I like a page source to be clean and organised (not like my bedroom), but also the goal here is to allow the browser to render the page as soon as possible. In other words, to reduce the time to first pixel:

<html>
  <head>
      <title>My Wonderful Page</title>
      <meta name="description" content="Some meaningful and reasonably long description">
      <script type="text/javascript" src="/js/head.js"></script>
      <link type="text/css" rel="stylesheet" href="/one/css/file.css" />
      
  </head>
  <body>
     <div>
         All sorts of HTML stuff.
     </div>

     <script type="text/javascript">
        
     head.js('https://ajax.googleapis.com/.../jquery.min.js',
                 'https://ajax.googleapis.com/../jquery-ui.min.js',
                 'http://mysite.com/js/site.js'
                );
    head.ready(function(){
      installFancyJS($(document));
    });
     </script>
   </body>
</html>

Let's go though this step by step.

Use a JS Loader. So the idea here is to do as little as possible in the header, and deport the heavy lifting to the end of the body. In your header, you should have only one and only one minimal script, and this script should allow you to load things later at your page bottom. Here I use head.js. It's got other fancy base features but load.js is also a good alternative if you like to make it even smaller. Let your page be pear shaped.

One CSS File. Not two, not three. One, and preferably on the same domain as your main site (so relative URLs are welcome here). Why is that? Here we reduce the number of extra requests the browser has to do to a minimum of erm ... one, and by having the CSS hosted on the same hostname, you avoid doing extra DNS queries, saving you precious milliseconds. Some people even argue that you should have your CSS in the page itself. I'm not sure about this one. It's true that it saves you the extra query entirely, but at the same time, your page is now heavier and therefore longer to download. There's probably a reasonable limit under which this actually saves time, but I'm not sure about its value. Of course in the development environment, you probably want to have your css neatly organized, so you don't have a giant ball of spaghetti monster to deal with. I've tried different techniques to achieve that, but didn't come with something I really like yet. Suggestions?

All sorts of HTML Stuff. Warning. Controversial bit. What? HTML stuff, controversial? Well yes, as it seems to me that with the advent of the uber-ubiquitous Ajax coolness, a large amount of people chose to ignore a fundamental fact of life (at least of life as a developer): Browsers were born to render HTML and dynamic web servers can generate HTML. For instance, I know a site where every time they need to display a table of something (let's say historical stock prices), they first display an empty table, and then, when all the page JavaScript is loaded, they make a second query to get the data to populate the table. It drives me mad. Not only I don't see the point* , but more importantly, you can imagine how it kills the 'time to useful pixel' of their pages. It's not that I'm against Ajax. not at all. I love it, I was doing it wayyyy before jQuery became popular. In fact you'll find here some posts I wrote about how to easily 'ajax' anything. But I kind of believe that if you want to do JS object models and get JSON from the server instead of HTML, you'll be much better off developing your backend as an API and generate your GUI using something like flex, or GWTK (please add yours to the list :)). I certainly reckon the incredible value and power of OO JS/Json for complex and specific information manipulation and display (down with flash and applets!!), but for general pages development, I prefer to stick with good old HTML, specially if the application is 'browsing' oriented.

One JS Function that does it all. I call it (observe my creative naming skills) 'installFancyJS', and it takes one argument: the jQuery** context it's going to used in. So what does this function do? Well, it installs callbacks and all sort of responsive code in the page just after it's loaded. More precisely in the given context. To give you a very minimal example:

function installFancyJS(context){
    installTopClick(context);
    ....
}
function installTopClick(context){
    $('div#topbar' , context).on('click', function(ev){
        $('html,body').animate({scrollTop: 0 },
                               { duration: 'slow', easing: 'swing'}
                              );
    });
}

The reason why I propagate the context everywhere is that when I get a new bit of HTML using Ajax, I want to be able to install the full set of Javascript features on the newly created slice of document. In here's an minimal example of Ajax callback that uses the function:

function(data){
                  var newbit = $(data);
                  container.replaceWith(newbit);
                  // install fancy js on the container's new content.                                                        
                  installFancyJS(container);
              }


That's is for now. I hope you enjoyed reading this and found some interesting/ridiculous/horrible things to talk about.

Jerome.




* But I see the reason: they got tied to the horrible datatables.net.
**yes I use jQuery, please rant and suggest in the comments if you know a better one.

Tuesday, 21 August 2012

The goodness of testing

Wall e-coyote testing a new rocket design
There’s a common view among programmers that testing (that is writing tests) is a painful thing you have to do to please your manager, or something you can avoid doing if your manager is not bothered. Let’s try to debunk that and show that testing is actually fun.

It guarantees code correctness. That’s obvious. Less obviously it forces you to think about what your code correctness actually is. By writing test, you will more easily think about those pesky edge cases that other users of your code will inevitably notice. Further techniques like property testing or mutation testing can also help automating thorough correctness.

It gives you a safety net when you refactor. Imagine you’ve finally decided to repay some technical debt and re-write your poorly written methods (don’t tell me you haven’t got any). If you’ve got good test coverage, no worries. You can refactor and rewrite your module, increase performance, cleanup poorly written code without worrying about breaking anything. At least anything that's tested.

It forces you to write better APIs. By putting you in the role of a user of your code/module/API, it forces you to think about the nicest way to use your module. This is creative, fun and interesting: How, as a client of your library, would you like to be able to use it. How would you like to interact with your piece of software? What do you expect from it? What should it expects from you? You decide, and because you're lazy and imaginative, you'll come to think about something neat. If anybody else uses your code in the future, you will attract a lot of developer love. Because people will go: "hum, that’s neat, and it works first time." That's lot of doughnuts for you.

You can see your test as a kind of contract about what is supposed to work now and forever more (biblical voice needed). It’s a contract between You, your future You, anyone who touches your code in the future, and also with the outside world. Why the outside world? I sometime think that everything that’s not tested doesn’t exists. It’s probably a philosophical view, but as a programmer, I like to think in binary terms. Something is there or something is not there. At least until quantum computers are on our desktops. So what about a feature that is not tested? It can break without anyone noticing, especially if it's a minor thing, or it can break and only the users notice (very bad). So is it there or not?

Well, if it can go away silently, I think it’s safer to assume it’s not there. Ask your sales team if they feel comfortable about selling stuff that can vanish at any time. Anything outside testing shouldn’t be assumed to be existing. That leads to what I deeply think about testing.

Testing does not help to make your product more reliable. Testing is your product.



Comments welcome!

Tuesday, 3 April 2012

Do you speak Franglais?

If you want to sound more clever than you really are in a French company, it's a good idea to forget about speaking French correctly and start speaking 'Franglais' instead. Franglais, spoken with the appropriate French accent, is a very effective way to impress your colleagues and your manager (in Franglais: "ennepluswone"), giving them the feeling that you hold and MBA from Harvard although the last time you were involved with the anglo-saxon's business culture, it was at 'Wall Street institute, 26 Rue de Lyon Paris'.

So here's a quick list to get you started in Franglais:

Cible -> Target
Concours -> Contest
Premieres étapes -> Early Stage
Mis en favoris -> Bookmarké (Bookmarked in English, but the french would prononce 'Bookmark-aide')
Délocalisé -> Offshore
Processus -> Process (you save two letters!)
Commuté  -> Switché (Switched in English)
Appel groupé -> Confcall
Tarifs -> Pricing
Défi -> Challenge
Concentré -> Focusé
Plein Ecran -> Full Screen
Atelier -> Workshop
Externalisé -> Outsourcé
Mondial -> Worldwide
Sauvegardé -> Backupé
Feuille de route -> Roadmap
Fonctionnalité / Attribut -> Feature
Retransmis -> Forwardé
Date butoir -> Deadline
Incité -> Incentivé
Recommandations  -> Guidelines
Discussion -> Chat
Collègue -> Co-worker
Personalisé -> Customé (Customis - aide)
Invité -> Guest
Avertissement -> Warning
Contenu -> Content
Ordonnanceur -> Scheduler

Ps: Thanks to Michel Poulain for his 'Bingo du Franglais'

Wednesday, 24 August 2011

LaTeX: Included graphics resolution

While most graphic files on the internet have a resolution of 72pixel/inch, you need to keep in mind that this resolution is often not suitable for printing. To illustrate that, let's take two images that have the same number of pixels (348 x 350):
One is set at 72pixels/inch:


And the other one is set at 144pixels/inch:


As you can see here, there's no way to tell the difference between them on the screen because your browser displays these images according to their sizes in pixels, regardless of their resolution.

Now if you write a LaTeX document that includes them both:

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\includegraphics{lowres.png}
\includegraphics{highres.png}
\end{document}

Here's what you get as the resulting pdf:


As you can see, the original 72px/in image will appear 'too big', pixelized and blurry on your piece of paper, whereas the 144px/in one will be twice as small and keep its sharpness.

So don't hesitate to experiment with resolution when making LaTeX based documents.

That's all for today!