Lesson 1 · Unit 03
The cost of JavaScript
Why a script costs more than an image of the same size
What you practise
- Download, parse, compile, run
- Code splitting
- Removing unused code
- Third-party scripts
Try a question from this lesson
Pick one
A page adds a 300 KB photo and a 300 KB script. Both take the same time to download. Which costs a phone more, and why?
Correct answer
The script: it must also be parsed, compiled and run
Why
A photo is decoded once, mostly off the main thread, and then it is just pixels. A script is text the phone has to turn into a running program, on its own CPU, and while it runs the page cannot answer taps. Equal bytes, very unequal work.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Four costs of a script
Every script is paid for four times: it is downloaded, parsed into a structure the engine understands, compiled, and executed.
Only the first depends on the network. The other three depend on the visitor's CPU, and a mid-range phone can be several times slower at them than the laptop the page was built on.
Compression shrinks the download only. The engine still processes the full, unpacked size.
download -> parse -> compile -> execute
network CPU CPU CPUConcept
Load on demand, drop what is unused
import("./chart.js") is a dynamic import: it returns a promise for the module. A bundler puts that module in a separate file, and the browser fetches it only when the line runs.
Tree shaking removes the other kind of waste. Because import and export statements can be read without running the code, the bundler can see which exports nothing imports and leave them out.
button.onclick = async () => {
const m = await import("./chart.js");
m.draw(data);
};10 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× true or false
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.