söndag 9 mars 2014

You might not need JavaScript

Are you about to code some awesome web stuff and have JavaScript enabled in your browser?

Turn that sh*t off!!!

Okay. Easy now.

I really like JavaScript. I like it even more than I like C#. There, I said it. And I mean it.

JavaScript is cool. JavaScript is freedom. Freedom from static typing, classes and compilation. Just code, save & browse. JavaScript is the language that help us deliver great things for the web. But what would happen if you would turn scripting off in the browser?

Oops. Dude, I can't do a thing on this web site.

Before we try to write the great things, I think we should begin to write stuff that just works. Focus on functionality. The features. Write code with quality built in from the start and without scripting dependencies. How about calling it NoScript First?

NoScript First is a development style, just like Test Driven Development and Mobile First.

Based on code I've read and written over the years I think far too many of us (myself included) misses things that really need to be there on the server: stuff like validation, security, unit tests and limiting allowed http methods. How come?

I think it is because we are humans (yes, coders are humans too). We like shortcuts. When a shortcut appear, we take it. Some shortcuts are great, some are not. Doing client script form validation, and not really testing if the server does the correct job is one of the really bad ones.

Enough.

Here's an example: a web page with user input to be sent, by posting a form to the server.

Turn JavaScript off and write the html (the view).


@using (Html.BeginForm("Add", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.TextBoxFor(model => model.Name)
    <input id="my-button" type="submit" value="Send"/>
}


Write the server code (the controller and the model). Make sure the user input is sanitized. Require an anti forgery token and limit the request to allow POST only.


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(Person person)
{.....}

public class Person
{
    [MyRequiredAttributeThatSanitizesStrings]
    public string Name { get; set; }
}


Try it, test it. Maybe even unit test it?
Turn JavaScript back on, hijack the submit event and do the great things.


$('#my-button').on('click', function (clickEvent) {
    clickEvent.preventDefault();
    // do the magic here
});


When you are done, try switching between JavaScript turned on and off. Do both ways work? Remember, keep it simple. NoScript First goes very well together with Test Driven Development, by the way.

Here is a full example asp.net mvc NoScript First project:
https://github.com/DavidVujic/blog/tree/master/NoScriptFirst


ps.
Check out some of my posts and videos on test driven development:
From the streets of test driven development: JavaScript
aspConf 2012 - Quick start: test driven development
ds.

Inga kommentarer: