Enforce DOMContentLoaded event on Window before jQuery Document ready

559 views Asked by At

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.

1

There are 1 answers

4
guest271314 On BEST ANSWER

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>