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
DOMContentLoadedevent. 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
deferby default. - Rule of thumb: own scripts with
defer, independent third-party scripts withasync.
Go
f, _ := os.Open("file.txt")
defer f.Close() // runs when the function ends- Several
defercalls run in reverse order (LIFO). - Typical for closing files, unlocking a mutex.
- Arguments are evaluated at the
defercall, not at the end. - Similar:
finally(try/catch/finally) and in Zig see Errors and defer.