Are You ready? / jQuery struggle

$(function() {
    console.log( "ready!" );
});

is the short form for:

$( document ).ready(function() {
    console.log( "ready!" );
});

Very unintuitive, this does not work:

$("input#myInput").bind("change", function(){
});

Instead of “change” You have to use “input”

$("input#myInput").bind("input", function(){
});

Inefficient jQuery Selectors

My PyCharm IDE warns me if I use inefficient jQuery selectors:

As I am a bit nosy I wanted to know “how” inefficient these selectors are. So I compared the inefficient

$("#items tbody");

with the optimized

$("#items").find("tbody");

Here is the test code:

window.onload = function () {
    test("unoptimized", function () {
        for(var i = 0; i < 100000; i++){
            $("#items tbody");
        }
        assert(true, "Test finished");
    });
    test("optimized", function () {
        for(var i = 0; i < 100000; i++){
            $("#items").find("tbody");
        }
        assert(true, "Test finished");
    });
};

I used the little test framework from the book Adventures of the JavaScript Ninja

The results vary from run to run but the optimized version just takes around 55% of the time which makes it almost twice as fast. Though the single execution is in the nanosecond range, if you heavily rely on using jQuery, it might be worthwhile to optimize your selector statements.

Code on GitHub

 

 

Bringing AJAX to Flask – Part 1

Flask is a micro web framework which is really fun to use. With the following snippet You have a complete web app working within seconds.

from flask import Flask # 1
 
app = Flask(__name__)   # 2

@app.route('/')         # 3
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()           #4

All this snippet does is

  1. Importing the Flask module,
  2. Creating the app,
  3. Defining an so called endpoint and finally
  4. Running the web app in a container.

Flask brings its own WSGI server called “werkzeug”. Please use it just for development purposes. It is not suitable for live applications. Continue reading “Bringing AJAX to Flask – Part 1”