Optimising JavaScript – London JS Create the Web – One: Selectors



Optimising JavaScript – London JS Create the Web – One: Selectors

0 0


ldnjs-optimisation-talk

Talk on Optimising Front-End JavaScript at LDN JS Nov 12

On Github jackfranklin / ldnjs-optimisation-talk

Optimising JavaScript

London JS Create the Web

Jack Franklin

Who is this guy?

Developer at Kainos.com Blogger at javascriptplayground.com Tweeter at @Jack_Franklin

This presentation

Is going to be about optimising your front-end JavaScript.

A lot of the examples will be jQuery based, because this is where I see the most mistakes.

It might seem like in places I have a go at jQuery, but that's not the case.

The stuff you do by default

var div = $("div");

Selecting by IDs (getElementById) and tags (getElementsByTagName)

We're not going to talk about. You all do it...right?

Modern Browser

In this presentation, I mean the latest build of Chrome, pretty much.

One: Selectors

In a modern browser, which is quicker?

1
$("div p");
2
$("div").find("p");

Number One

JS Perf Link

But Why?

Because of querySelector and querySelectorAll.

So what about browsers without?

document.querySelector = false;
document.querySelectorAll = false;

JS Perf Link

Two: Loops

paras = $("p");

1
paras.each(function(index, item) {
  console.log(index, "and item", item);
});
2
var len = paras.length;
for (var i = 0; i < len; i++) {
  console.log(i, "and item", paras[i]);
}
3
var i = paras.length;
while (i--) {
  console.log(i, "and item", paras[i]);
}

Results

JS Perf Link

FF Nightly reported while(i--) quickest.

Accessing Attributes

$("p").attr("id");
$("p")[0].id;
$("p").get(0).id;
document.getElementsByTagName("p")[0].id

Unsurprisingly...

JS Perf Link

If you're working with a jQuery set, avoid attr if you can.

If you can avoid jQuery, do it.

DOM Insertion

1
var i = 0;
var newUl = $("<ul />").appendTo("body");
while( i < 100 ) {
  $("<li />", {
    "text" : i+1
  }).appendTo(newUl);
  i++;
}
2
var i = 0;
var newUl = $("<ul />");
while( i < 100 ) {
  $("<li />", {
    "text" : i+1
  }).appendTo(newUl);
  i++;
}
newUl.appendTo("body");
3
var i = 0;
var newUl = "<ul>";
while( i < 100 ) {
  newUl += '<li>' + (i++) + '</li>';
}
newUl += '</ul>';
  
$('body').append(newUl);

Keep your manipulation to a minimum

JSPerf Link

Creating new Elements

1
var newSpan = $("<span />", {
  text: "Hello",
  id: "hey"
});
$("#test").append(newSpan);
2
var newSpan = $(document.createElement("span"), {
  text: "Hello",
  id: "hey"
});
$("#test").append(newSpan);

Native JS FTW

JSPerf Link

General Tips

Use for..in for Objects, for for Arrays

Cache lengths in loops.

DOM Manipulation to a minimum.

Change classes, not styles.

JSPerf is great for trying things out.

Thanks!

@Jack_Franklin

(PS: you should totally pre-order my book.)