2

So, I know the general order of when a script executes...

According to this defered scripts are executed before the DOMContentLoaded event gets fired, but do not block the page and subsequent scripts from loaded (unless they are also defered). Please correct me if I'm wrong here.

This seems like another way of including scripts and executing them after the DOM is available, so when should I use this over document.addEventListener('DOMContentLoaded', function(){...});? And as of ES6, what is the best practice for executing/loading scripts after the DOM becomes available? I assume addEventListener is preferred over jQuery's $(document).ready or window.onload (again, correct me if I'm wrong...), but where does defer or other methods of loading scripts come into play?

Logan
  • 181
  • 1
  • 10
  • 1
    Less code means less surface area for bugs, which is one small reason why one might prefer `defer` – CertainPerformance Apr 06 '20 at 03:35
  • Defer is used on script elements, which means you can just reference your script files easily. For more details on how defer interacts vs `DomContentLoaded`, I suggest you check this out: https://stackoverflow.com/questions/42950574/are-deferred-scripts-executed-before-domcontentloaded-event – Omar Sourour Apr 06 '20 at 04:10
  • 1
    I had saw that question, unfortunately it doesn't answer my question about best practices.. when is one preferred over the other, or is there a specific case where I'd rather use defer than executing code when the dom loaded event is fired? – Logan Apr 06 '20 at 16:00

0 Answers0