Ajax requests on jsFiddle

Did you know that you could create XHR requests on jsFiddle? If you didn’t know,  just keep reading..

To improve user experience jsFiddle has created the echo features. One of its features is to provide to developers the possibility to create XHR requests. It is very simple to use:


  <div class='wrapper'>
  <p>JSON will be received in 3 seconds</p>
  <div id='post'></div>
  </div>

This is my HTML, a simple div with id=post will be appended with the response from the request.

To make a request, I have used jQuery and it looks like this:


// My request

$.ajax({
  type: "POST",
  url: '/echo/json/',
  dataType: "json",
  data:{
    json: JSON.stringify({
      text: 'Response from server',
    }),
    delay: 3
  },
  }).done(function(response) {
    show_response(response);
});

// append data from response to my div
show_response = function(obj, result) {
    $('#post').append(obj.text);
};

My request is just a simple jQuery ajax() call. There are some things that we have to provide.

The data has to be a POST call.  The url points to   ‘/echo/json/’ because I’ve chosen json to represent my data, but there is other types available (including XML).  The ‘json’ object that you define on the request, will be the object that you’ll get on the response. The optional ‘delay’ parameter, it’s a time in seconds after which data should be returned.

And this is pretty much it! Simple and very useful if you, like me, use jsFiddle to share code samples, help anyone or just quick testings!

You can see the live example here.

Advertisements

Javascript pre-compiled templates with Handlebars.js

Handlebars is a template engine based on mustache.  The code blocks are delimited by {{ .. }}

Here’s an example of a Handlebars.js template:

<script id="todos-template" type="text/x-handlebars-template">
  {{#each todos}}
    <div class='todo-item'>
    <p>Title: {{ this.title }} </p>
    </div>
  {{/each}}
</script>

Rendering a template is a two stage process: Compile and Execute.

1 – To compile we should do this:


var source = $("#todos-template").html();
var template = Handlebars.compile(source);

2 – To execute we do this:


var context = {
  todos:[
    {title: "Task 1"},
    {title: "Task 2"}
  ]
}

var html = template(context);

See live demo

The process of compiling the template is in fact, converting the template from string, to javascript function, that we call later with our data. The compilation is the most expensive in terms of performance. So if you want performance, make sure you compile each template once and, cache the template functions and, reuse whenever you need.

So, now is where things get interesting. One of the most important features of Handlebars.js, is the support for pre-compiled templates. Pre-compiled templates, as the name states, are templates previously compiled instead being compiled in run time.

So this means, that we can get rid of the most expansive part of the template process!

Handlebars includes support for pre-compiling file-based templates. It is possible to have a script that finds all your templates (in separated files), compiles them and put them in one single file!

To achieve the compilation as a build step, we need to have installed node.js and npm.

After installing both, we need to install also the Handlebars npm package like this:

$ npm install handlebars -g

The -g flag installs the package globally, so it can be used in any project.

And now, we are ready to start using the precompiler. On the console you can do:


$ handlebars <input> -f <output>

The compiler will insert templates in Handlebars.templates. If, for example, you had an input file todos.handlebars, the compiler would insert it at Handlebars.templates.todos.
In my previous example and having a folder called “templates” with all my Handlebars.js templates, I would compile them like this:


$ handlebars templates/ -f templates.js

Handlebars then, would create a single file with the combined templates under templates folder in a templates.js file that we need to include in our page.

Back to my example, now, instead of having:


var source = $("#todos-template").html();
var template = Handlebars.compile(source);

I can have just:

var template =  Handlebars.templates.todos;

The main idea to retain is that skipping the compilation at run time, we are avoiding the most expensive step of template rendering in terms of performance!

Check on my github the code for a simple example using precompiled Handlebar.js templates and Backbone.js

List of references:
http://handlebarsjs.com/