1

Say I have the following two script tags somewhere on my page:

<script>
    window.addEventListener("DOMContentLoaded",
        function()
        {
            console.log("DOM loaded");
        }
    );
</script>
...
<script>
    $(document).ready(
        function()
        {
            console.log("Document ready");
        }
    );
</script>

Is there any easy way to enforce that the DOMContentLoaded event fires before $().ready?

This is a simplified example of my actual problem. The real problem I'm facing is that the DOMContentLoaded event is registered in a third-party library that I am including at the bottom of my page's body, and I have far too many $().ready calls to change them all quickly. I could, in theory, change window.addEventListener to document.addEventListener without creating any problems, but because I'm including jQuery in my page's head, all $().ready calls still fire before document.addEventListener("DOMContentLoaded"...), as explained here, and I can't reasonably move the include location of jQuery or this third-party library. I would also like to avoid making changes to the third-party library if possible.

Community
  • 1
  • 1
Jimmy P
  • 1,790
  • 4
  • 17
  • 32

1 Answers1

1

You can use $.holdReady()

<script>
    $.holdReady(true);
    window.addEventListener("DOMContentLoaded", function() {
      console.log("DOM loaded");
      $.holdReady(false);
    });
</script>
...
<script>
    $(document).ready(function() {
      console.log("Document ready");
    });
</script>
guest271314
  • 1
  • 15
  • 104
  • 177
  • If jQuery might not be included, would it be sufficient to surround both `holdReady` calls in `if (typeof $() != 'undefined')`? – Jimmy P Jan 05 '17 at 18:52
  • @JimmyP _"If jQuery might not be included"_ Not sure what you mean? Is not premise of Question `.ready()` handler being called before `DOMContentLoaded` event? – guest271314 Jan 05 '17 at 18:55
  • Yeah, sorry. That was the original question, but now I am curious; if one of my pages includes this third-party library that registers the `DOMContentLoaded` event while jQuery isn't present on the page, it's going to throw an undefined error. – Jimmy P Jan 05 '17 at 19:00
  • 1
    `$` could be defined as a function or value other than `jQuery()`, you can check `window.jQuery` – guest271314 Jan 05 '17 at 19:02