EMZETT.
Login

defer: scripts in HTML and the keyword in Go

In short: In HTML <script defer> makes a script load in parallel but run only after the page has been built. In Go defer postpones a function call until the surrounding function ends.

In more detail: Both meanings have to do with “run later”. The HTML attribute improves load time, the Go keyword takes care of clean-up.

In detail

HTML

  • Normal: <script src="a.js"> stops page parsing, loads and runs the script immediately. That delays display.
  • defer: loads in parallel, runs after HTML parsing is finished, in document order, before the DOMContentLoaded event. External scripts only.
  • async: loads in parallel, runs right after loading, order not guaranteed. Good for independent scripts such as analytics.
  • type=“module”: modules behave like defer by default.
  • Rule of thumb: own scripts with defer, independent third-party scripts with async.

Go

f, _ := os.Open("file.txt")
defer f.Close()   // runs when the function ends
  • Several defer calls run in reverse order (LIFO).
  • Typical for closing files, unlocking a mutex.
  • Arguments are evaluated at the defer call, not at the end.
  • Similar: finally (try/catch/finally) and in Zig see Errors and defer.

See also: Events, Function