'Using defer to implement jQuery-ready-like function in the same HTML
I would like to remove my jQuery and I need to replace $(function() { ... }); with something similar. I have seen people use the new HTML property defer but they use it to call another script rather than calling codes in the the same HTML source. How can I use defer to implement the same ready feature in my HTML code without calling another script?
<div style="margin-top: 100px">.</div>
<div>AAAA</div>
<script defer>alert('hi')</script>
<div>BBBB</div>
Solution 1:[1]
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 thedeferattribute to a script tag results in the script execution being delayed until immediately beforeDOMContentLoadedwould fire (when the DOM is parsed), and makes sureDOMContentLoadeddoesn't actually fire before the full script has been executed. Please note thatdefermust not be used when thesrcattribute is missing (that is, it's only available for external scripts).DOMContentLoadedlistener (orreadyStateChangelistener if you enjoy complicating things).- Adding your
scripttag 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | connexo |
