On Page Performance

In this lesson we'll learn:

Pragmatic Approaches

requestAnimationFrame

// Read
var h1 = element1.clientHeight;

// Write (invalidates layout)
element1.style.height = (h1 * 2) + 'px'

// Read (triggers layout)
var h2 = element2.clientHeight;

// Write (invalidates layout)
element2.style.height = (h2 * 2) + 'px'

// Read (triggers layout)
var h3 = element3.clientHeight;

// Write (invalidates layout)
element3.style.height = (h3 * 2) + 'px'

Enter requestAnimationFrame()

function repeatOften() {
  // Do whatever
  requestAnimationFrame(repeatOften);
}
requestAnimationFrame(repeatOften);

After watching the layout thrashing video, head over to the layout thrashing exercise

Web Workers

You can invoke a worker from any JavaScript file like this:

// script.js
const input = document.querySelector("#input");
const display = document.querySelector("#display");

if (window.Worker) {
  const myWorker = new Worker("worker.js");

  input.onchange = function () {
    myWorker.postMessage(input.value);
    console.log("Message posted to worker");
  };

  myWorker.onmessage = function (e) {
    display.textContent = e.data;
    console.log("Message received from worker");
  };
} else {
  console.log("Your browser doesn't support web workers.");
}

And then just create a worker.js file like this:

// worker.js
onmessage = function (e) {
  console.log("Worker: Message received from main script");
  const result = e.data;
  console.log("Worker: Posting message back to main script");
  postMessage(`Worker received ${result} from the main script`);
};

Running DevTools on Node.js apps

Try killing the current process and running

node --inspect server/server.js

Exercise

Now try to play around with the Performance tab yourself on this page.