0

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>
ar2015
  • 5,558
  • 8
  • 53
  • 110
  • Yes, you cannot defer a script body code, only its source file. How does your question relates to the provided HTML code? What is your problem exactly? PS: [Window/DOMContentLoaded_event](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) – Roko C. Buljan Mar 26 '22 at 12:54
  • @RokoC.Buljan, how to implement ready function? Look at the comment under https://stackoverflow.com/a/800010 . Seems `DOMContentLoaded` is not a perfect solution. – ar2015 Mar 26 '22 at 12:57
  • Just write ` – NNL993 Mar 26 '22 at 13:10
  • @NNL993, not an attractive solution nor practical in every scenario. jQuery ready works flawlessly. – ar2015 Mar 26 '22 at 13:45
  • `DOMContentLoaded` is your cleanest option for inline scripts (which you shouldn't use in the first place). I don't think that 6 year old comment is any relevant these days. – connexo Mar 26 '22 at 13:55

1 Answers1

0

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):

  1. 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).
  2. DOMContentLoaded listener (or readyStateChange listener if you enjoy complicating things).
  3. 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.

connexo
  • 53,704
  • 14
  • 91
  • 128