Loading main.js with defer
Should I be deferring the loading of javascript on this site?
What is the script “defer” attribute? #
Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script .
The defer boolean attribute tells a browser that the script is meant to be executed after the
document has been parsed, but before firing the DOMContentLoaded event.
Adding the defer attribute to the JS HTML template #
Note: it might be possible to accomplish the same thing with the templates.Defer directive. See
the end of
Using Tailwindcss in a Hugo theme
.
I’ve added defer to the script that that’s added by the Hugo js.html template. This is the
template that’s generated when a Hugo theme is created with hugo theme new.
{{- with resources.Get "js/main.js" }} {{- $opts := dict "minify" (not
hugo.IsDevelopment) "sourceMap" (cond hugo.IsDevelopment "external" "")
"targetPath" "js/main.js" }} {{- with . | js.Build $opts }} {{- if
hugo.IsDevelopment }}
<script src="{{ .RelPermalink }}" defer></script>
{{- else }} {{- with . | fingerprint }}
<script
src="{{ .RelPermalink }}"
integrity="{{ .Data.Integrity }}"
crossorigin="anonymous"
defer
></script>
{{- end }} {{- end }} {{- end }} {{- end }}
Simplifying main.js to account for deferred loading #
Since defer prevents the script from being executed until the document has been parsed, and is
executed before the DOMContentLoaded event, I think I can remove the call to
document.addEventListener("DOMContentLoaded") call from the script.
Instead of:
document.addEventListener("DOMContentLoaded", function () {
const searchInput = document.getElementById("semantic-search");
// ...
}
It can be simplified to:
const searchInput = document.getElementById("semantic-search");
if (searchinput) {
// ...
}
A minor change, but one less level of nesting works for me.