You basically have three standard options at your disposal, two being explicit, and one being implicit and relying on how the browser parses the document (top-down, element by element):
defer
. Adding the defer
attribute to a script tag results in the script execution being delayed until immediately before DOMContentLoaded
would fire (when the DOM is parsed), and makes sure DOMContentLoaded
doesn't actually fire before the full script has been executed. Please note that defer
must not be used when the src
attribute is missing (that is, it's only available for external scripts).
DOMContentLoaded
listener (or readyStateChange
listener if you enjoy complicating things).
- Adding your
script
tag right before the closing </body>
tag.
Please note that scripts that have type="module"
are automatically deferred.
Personally, I stopped using jQuery around 2015, and since that, have been working with DOMContentLoaded
ever since, with not a single issue in all those years.