Decaying Code

Where code comes to die

About the author

Maxime Rouiller is a passionate .NET technology specialist, working for 7 years in large software development, advocating Agile and TDD. Aware of the latest technological trends, he intervenes as a specialist in the .NET Montréal usergroup and acts regularly as a speaker for Web Form programmers on the MVC platform.

View Maxime Rouiller's profile on LinkedIn

Month List

Browser Detection is bad. Feature Detection is better.

Context (Or a little bit of history)

Those who did websites in the beginning of the decade had to work with IE6, Netscape Communicator/Navigator and Opera. Some more browser introduced themselves along the years but most supported different things.

Netscape supported the blink tag (oh how I hate thee). Internet Explorer supported ActiveX and Opera was not popular enough to think about it.

We were in an era where people thought of the web as the blue “E” icon. People were not aware of browsers that much and those who had Netscape probably had it from an AOL promotion.

Since we wanted to display the same thing to every users as much as possible, people either started detecting browsers to clearly say on which browser their website is supported or they just didn’t do any checking at all!

That’s the main reason some internal web applications still display “Works better with IE6”.

Browser Detection

Browsers back then differed a lot from each other. So we had to know if we could use ActiveX or whether we wanted to piss off our users with a blink tag.

The rendering of all this of course was different per browsers.

Here is the script to detect which browsers you are running. I will not copy it here (too large) but you can see that it grows.

Once people knew which browser was running, they knew which feature was supported! So everything was perfect, right?

Not exactly. What if the feature was deprecated in the next version? What if the browser had that functionality disabled by an option? What if a new browser that your script don’t know come in? Why couldn’t he use that feature if he supported it?

This caused a lot of problem. Mostly because detecting a browser didn’t guarantee you anything beside that the user was sending you a UserAgent string that pleased you.

The browser detection was broken from the start and something had to be done to detect whether something was going to work or not. Irrespectively of the browser.

Feature Detection

Then came feature detection. The first real push for it was by Mr. John Resig himself when he posted “Future-Proofing JavaScript Libraries”. Today, jQuery allow developers to access a ton of features that would have taken individual developers months to develop and maintain. jQuery allows you to implement binding of events without knowing whether you should use attachEvent or addEventListener.

If you have the time, go see the development version of jQuery. It’s commented and will allow you to find their hacks to offer everyone the same functionalities. This allows you to manipulate the browser without having to know which one it is. It allows you to do Ajax in IE6 with ActiveX or with IE7 (or higher) with the proper object without knowing if your browser supports ActiveX.

Today, assuming everyone use a frameworks which smooth the basic differences between the browsers, the only thing you might be checking nowadays is HTML5 feature compatibility.

Introducing Modernizr

Modernizr is a library which does Feature detection and that can be tailor cut to your needs. In its complete version, it allows you to detect easily the following features (not a complete list):

  • SVG/Canvas support
  • Web sockets
  • Web SQL Database
  • Web workers
  • HTML5 Audio/video
  • Hash Change event
  • WebGL
  • Geolocation
  • Much more…

Modernizr once referenced in your webpage allow you to tailor your own code to know if you should gracefully degrade some feature or not.

Here is an example on how you could use Modernizr when implementing geolocation in your application:

Modernizr.load({
  test: Modernizr.geolocation,
  yep : 'geolocation.js',
  nope: 'no-geolocation.js'
});

This simple code allows you to load a different JavaScript based upon the feature of a browser.

Modernizr offer support for IE6+, FireFox 3.5+, Opera 9.6+, Safari 2+, Chrome, iOS, Android, etc.

Conclusion

With the current quantity of browsers that supports different functionalities at various levels, we should not be implementing for specific browsers but rather for specific features. We would want those feature implemented in all browsers but with the fragmentation of the browser market, it’s just not going to happen soon.

So please, no more “This site works better with [INSERT BROWSER]”. Target a feature, test for it, and offer different (or no) implementation if the feature is not available. This will make your code cleaner and more efficient.

So stop the Browser detection madness and embrace the feature detection.

It might sound counter intuitive to some but it makes sense. So be ready for the future.

If you are using HTML5, use feature detection rather than browser detection.


Categories: jquery | opinion | productivity
Permalink | Comments (0) | Post RSSRSS comment feed

DevCamp Montreal 2011– jQuery Presentation

For those who will attend tonight’s presentation fast talk on jQuery, here is my presentation file that I will be using tonight.

It’s available for download by clicking the link bellow!

Download the presentation file here


Categories: jquery | presentation
Permalink | Comments (0) | Post RSSRSS comment feed

Ajax with jQuery and ASP.NET MVC

Requirements

What should I learn first?

When doing AJAX with ASP.NET MVC, there is no “UpdatePanel” or high level abstraction that helps you do all the magic. You need to get your hands dirty. That means learning how to do actual JavaScript without having the framework do all the job for you.

My favorite tool is jQuery when it comes to JavaScript. It’s simple, small and allows you to do in a few line of codes in 5 minutes what would take me 3 days an 2000 lines of code.

What should be on your reading list?

Document Ready Event

First, do not forget to put any jQuery code inside the following snippet:

$(document).ready(function () {
    // all code need to go there.
});

Selectors

The three most important selectors (in my opinion) are the following :

Those three selectors will include around 80 to 90% of all the selector you will require. The others, you can pick up along the way!

Manipulation

Here, we are talking about manipulating elements from the HTML page. We will need those since they are required for removing and adding HTML into the page. It’s basically what the UpdatePanel for WebForms do but we’ll do it manually and be more specific in what we want.

Here what I consider essential :

  • remove() – Allows you to remove an element from the DOM. This is useful when wanting to remove an element directly.
  • append()/prepend() – Allows you to insert an element inside the selected tags (either before or after the existing elements of that tag)
  • replaceWith() – Replace the element with what’s given in parameters. When using this, make sure that the replaced element have the same usable selector or it will harder to reselect that element.

And now, we have nearly everything that we need to start being AJAX-y!

I already know all that, let me do AJAX!

So what’s the easiest with jQuery to do AJAX?

$.get()

This method will basically do an HTTP Get on the selected URL and return the data inside the success function callback.

Let’s say I want to add the result of my AJAX request to the following tag:

<div id="result">
</div>

It would be as easy as doing this :

$.get('/Controller/Action/', null, function (data) {
    $("#result").empty(); // clears the content
    $("#result").append(data); // append the data into the div
});

Wasn’t that easy?

The MVC Side

Of course, if your MVC Controller is returning an JsonResult, you could use $.getJSON instead and data would be an object instead of pure HTML. In fact, your controller can even return a simple string and it would work. But how do you make your controller returns only what you need? Actions can be split in 2 with MVC to respond differently whether the request is standard or an AJAX request. Here is what it would look like:

public ActionResult MyAction() 
{
    if(Request.IsAjaxRequest())
        return View("nameOfMyPartialView");
    else
        return View();
}

That’s it! And now if you want to return an object as JSON:

public ActionResult AnotherAction()
{
    if(Request.IsAjaxRequest())
    {
        // The following line return Json to AJAX requests
        return Json(new { name = "Maxime Rouiller"}, JsonRequestBehavior.AllowGet);
    }

    // we still return normal HTML to standard requests.
    return View();
}

I hope you enjoyed this small example. If you are still curious or if you are simply stuck with something, ask away!


Categories: mvc | jquery | ajax
Permalink | Comments (0) | Post RSSRSS comment feed

Tip & Trick : Intellisense for Javascript in Visual Studio 2010

I know pretty much everyone already knows that but I would love to remember everyone how to get Intellisense working in Visual Studio 2010.

I mainly use jQuery and the API is huge. A bit huge to remember sometimes and I always have the documentation opened in a browser window. To alleviate my pain, I love to use the Intellisense and here is how you get it to work.

First, open your javascript file. Then, drag and drop the file you want to reference at the top of the document.

That's it. You now have Intellisense if a "vsdoc" of your library is available. I'll even throw you something more for you to enjoy. When you declare an event handler for a jQuery element and that you want to access the "event" element. That event is of type jQuery.Event. Just add "/// <param name=variableName type=jQuery.Event />" right after the declaration and it will enable the Intellisense on that variable.

Enjoy!


Permalink | Comments (0) | Post RSSRSS comment feed