Performance and deploy

Level recap · Performance and deploy · Level 1

Build and speed

Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.

What this level teaches: Write the build that makes the site small and fast, and check it against a speed budget.

10 classesLevel exam

Take the level exam
  1. 1The build folder

    Copy the site into dist, fresh every time.

    The idea

    Ticket CL-501 from the web lead: the shop front's files live in src/. The host serves only what is in dist/, so every release starts with a build that fills dist/.

    A build reads the source folder and writes the output folder. fs.readdirSync("src") lists the names in a folder, fs.copyFileSync(from, to) copies one file, and path.join("src", name) builds the path.

    The code

    const fs = require("fs");
    const path = require("path");
    fs.rmSync("dist", { recursive: true, force: true });
    fs.mkdirSync("dist");
    const names = fs.readdirSync("src");
    for (const name of names) {
      fs.copyFileSync(path.join("src", name), path.join("dist", name));
    }
    console.log("Built " + names.length + " files");

    What it shows

    PASS Every file in src is copied into dist
  2. 2Folders inside folders

    Copy a whole tree of folders.

    The idea

    Ticket CL-502: the pictures moved to src/images/ and the icons to src/images/icons/. The build copies only the top files, so the live pages have no pictures.

    fs.readdirSync(dir, { withFileTypes: true }) gives one entry per name, and entry.isDirectory() tells a folder from a file. A function that calls itself for each folder walks the whole tree: copy a file, or make the folder in dist and walk into it.

    The code

    const fs = require("fs");
    const path = require("path");
    function copyDir(from, to) {
      fs.mkdirSync(to, { recursive: true });
      let count = 0;
      for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
        const a = path.join(from, entry.name);
        const b = path.join(to, entry.name);
        if (entry.isDirectory()) {
          count += copyDir(a, b);
        } else {
          fs.copyFileSync(a, b);
          count++;
        }
      }
      return count;
    }
    fs.rmSync("dist", { recursive: true, force: true });
    …

    What it shows

    PASS Files in folders inside folders are copied
  3. 3Smaller CSS

    Remove what the browser does not need.

    The idea

    Ticket CL-503: the speed report says style.css is sent with all its comments, line breaks and spaces. Browsers do not need any of them, but every visitor downloads them.

    Minifying removes comments /* … */, line breaks, and spaces around { } : ; ,. A regular expression does each step: css.replace(/\/\*[\s\S]*?\*\//g, "") removes the comments.

    The code

    const fs = require("fs");
    function minify(css) {
      return css
        .replace(/\/\*[\s\S]*?\*\//g, "")
        .replace(/\s+/g, " ")
        .replace(/\s*([{}:;,])\s*/g, "$1")
        .trim();
    }
    const css = fs.readFileSync("src/style.css", "utf8");
    const small = minify(css);
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/style.css", small);
    console.log("style.css: " + Buffer.byteLength(css) + " bytes, now " + Buffer.byteLength(small) + " bytes");

    What it shows

    PASS minify removes the comments and line breaks and keeps every rule
  4. 4File names that change with the content

    A new version gets a new name.

    The idea

    Ticket CL-504: after each release some customers still get the old app.js from their browser's cache, and the page breaks.

    Give each file a name made from its content: app.3f9a1c2e.js. A new version gets a new name, so no browser can use an old copy, and the host can tell browsers to keep these files for a year.

    The code

    const fs = require("fs");
    const path = require("path");
    const crypto = require("crypto");
    function hashName(file, text) {
      const hash = crypto.createHash("sha256").update(text).digest("hex").slice(0, 8);
      const ext = path.extname(file);
      return path.basename(file, ext) + "." + hash + ext;
    }
    const js = fs.readFileSync("src/app.js", "utf8");
    const name = hashName("app.js", js);
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync(path.join("dist", name), js);
    const html = fs.readFileSync("src/index.html", "utf8");
    fs.writeFileSync("dist/index.html", html.replace('src="app.js"', 'src="' + name + '"'));
    console.log("app.js -> " + name);

    What it shows

    PASS hashName puts 8 characters of the content's sha256 in the name
  5. 5Picture sizes

    Keep the space for each picture before it arrives.

    The idea

    Ticket CL-505: the product page jumps while it loads: the text moves down each time a picture arrives. The speed report calls this layout shift.

    When an <img> has width and height, the browser keeps the right space for it before the picture arrives, so nothing jumps. The size of each picture is in images.json, like { "hero.jpg": { "width": 1600, "height": 900 } }.

    The code

    const fs = require("fs");
    function addSizes(html, sizes) {
      return html.replace(/<img [^>]*>/g, (tag) => {
        const m = /src="images\/([^"]+)"/.exec(tag);
        const size = m && sizes[m[1]];
        if (!size || /\swidth=/.test(tag)) return tag;
        return tag.replace("<img ", '<img width="' + size.width + '" height="' + size.height + '" ');
      });
    }
    const html = fs.readFileSync("src/index.html", "utf8");
    const sizes = JSON.parse(fs.readFileSync("images.json", "utf8"));
    const out = addSizes(html, sizes);
    const count = (s) => (s.match(/<img [^>]*width=/g) || []).length;
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/index.html", out);
    console.log("Sizes added to " + (count(out) - count(html)) + " pictures");

    What it shows

    PASS Each img gets the width and height from images.json
  6. 6Load pictures when they are needed

    Pictures far down the page wait for the scroll.

    The idea

    Ticket CL-506: the catalog page loads every product photo at once, even the ones far down the page that most visitors never reach.

    loading="lazy" on an <img> tells the browser to load the picture only when the visitor scrolls near it. Do not put it on the first picture, the big one at the top: it is seen at once and should load first.

    The code

    const fs = require("fs");
    function lazyImages(html) {
      let seen = 0;
      return html.replace(/<img [^>]*>/g, (tag) => {
        seen++;
        if (seen === 1 || /\sloading=/.test(tag)) return tag;
        return tag.replace("<img ", '<img loading="lazy" decoding="async" ');
      });
    }
    const out = lazyImages(fs.readFileSync("src/index.html", "utf8"));
    const all = (out.match(/<img /g) || []).length;
    const lazy = (out.match(/loading="lazy"/g) || []).length;
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/index.html", out);
    console.log("Lazy loading on " + lazy + " of " + all + " pictures");

    What it shows

    PASS Every picture after the first has loading="lazy" and decoding="async"
  7. 7Scripts that do not block the page

    defer lets the page draw first.

    The idea

    Ticket CL-507: on phones the page stays white for a second before anything shows. The speed report says: render-blocking script in head.

    A <script src> in <head> stops the browser: it downloads and runs the script before it draws anything. With defer, the script downloads while the page is drawn and runs once the page is read, in the same order as before.

    The code

    const fs = require("fs");
    function deferScripts(html) {
      const end = html.indexOf("</head>");
      const head = html.slice(0, end).replace(/<script [^>]*>/g, (tag) => {
        if (!/\ssrc=/.test(tag) || /\s(defer|async)[\s>=]/.test(tag) || /type="module"/.test(tag)) return tag;
        return tag.replace("<script ", "<script defer ");
      });
      return head + html.slice(end);
    }
    const html = fs.readFileSync("src/index.html", "utf8");
    const out = deferScripts(html);
    const count = (s) => (s.match(/<script defer /g) || []).length;
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/index.html", out);
    console.log("Scripts deferred: " + (count(out) - count(html)));

    What it shows

    PASS Plain scripts in the head get defer
  8. 8Fonts without the wait

    Show the text at once, and fetch the font early.

    The idea

    Ticket CL-508: on a slow phone the headings stay invisible for 3 seconds, then the font appears all at once.

    By default a browser hides text until its web font arrives. font-display: swap; in the @font-face rule shows the text at once in a system font and swaps to the web font when it is ready.

    The code

    const fs = require("fs");
    function swapFonts(css) {
      return css.replace(/@font-face\s*{([^}]*)}/g, (rule, body) => {
        if (/font-display/.test(body)) return rule;
        return "@font-face {" + body.replace(/\s*$/, "") + "\n  font-display: swap;\n}";
      });
    }
    const css = fs.readFileSync("src/style.css", "utf8");
    const fonts = [];
    for (const file of css.match(/fonts\/[\w.-]+\.woff2/g) || []) {
      if (!fonts.includes(file)) fonts.push(file);
    }
    const links = fonts.map((f) => '<link rel="preload" href="' + f + '" as="font" type="font/woff2" crossorigin>\n').join("");
    const html = fs.readFileSync("src/index.html", "utf8").replace("</head>", links + "</head>");
    fs.mkdirSync("dist", { recursive: true });
    fs.writeFileSync("dist/style.css", swapFonts(css));
    fs.writeFileSync("dist/index.html", html);
    console.log("Preloaded " + fonts.length + " fonts");

    What it shows

    PASS Each @font-face without font-display gets font-display: swap
  9. 9Cache headers

    Tell browsers what they may keep, and for how long.

    The idea

    Ticket CL-509: the shop's own host serves dist/. Hashed files never change, so browsers may keep them. index.html changes with every release, so browsers must check it each time.

    The Cache-Control header says how long a browser may keep a file. public, max-age=31536000, immutable means a year, without asking again: right for hashed names like app.3f9a1c2e.js (a dot, 8 characters from 0-9 and a-f, then the extension). no-cache means keep it, but ask the server each time whether it changed: right for HTML. public, max-age=3600 (an hour) fits the other files.

    The code

    const http = require("http");
    const fs = require("fs");
    const path = require("path");
    const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".jpg": "image/jpeg", ".png": "image/png", ".svg": "image/svg+xml", ".woff2": "font/woff2" };
    function cacheFor(file) {
      if (file.endsWith(".html")) return "no-cache";
      if (/\.[0-9a-f]{8}\.\w+$/.test(file)) return "public, max-age=31536000, immutable";
      return "public, max-age=3600";
    }
    const server = http.createServer((req, res) => {
      const url = req.url.split("?")[0];
      const file = path.join("dist", url === "/" ? "index.html" : url);
      if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("Not found");
        return;
      }
      res.writeHead(200, { "Content-Type": TYPES[path.extname(file)] || "application/octet-stream", "Cache-Control": cacheFor(file) });
    …

    What it shows

    PASS Each file comes back with its content and its Content-Type
  10. 10A speed budget

    A release that is too heavy does not ship.

    The idea

    Ticket CL-510: the team agreed on a budget for the shop front: the JavaScript stays under 170 KB, the CSS under 50 KB, the pictures under 900 KB. A release that goes over must stop before it ships.

    A speed budget turns "the site feels slow" into numbers a build can check. budget.json has a limit in bytes for each kind of file, like { "js": 170000, "css": 50000, "images": 900000 }. fs.statSync(file).size is a file's size in bytes.

    The code

    const fs = require("fs");
    const path = require("path");
    const budget = JSON.parse(fs.readFileSync("budget.json", "utf8"));
    const KIND = { ".js": "js", ".css": "css", ".jpg": "images", ".png": "images", ".svg": "images", ".webp": "images" };
    const totals = {};
    function walk(dir) {
      for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
        const file = path.join(dir, entry.name);
        if (entry.isDirectory()) {
          walk(file);
        } else {
          const kind = KIND[path.extname(file)];
          if (kind) totals[kind] = (totals[kind] || 0) + fs.statSync(file).size;
        }
      }
    }
    walk("dist");
    let over = false;
    …

    What it shows

    PASS Each kind's line shows the total of its files, in folders too

Ready for the exam? The level exam is one real task that uses what this recap covers.

Take the level exam