Running a function just before $(document).ready() triggers

萝らか妹 提交于 2019-12-04 01:23:17

This would be a time where I would trigger a custom event that all of your other files would bind to, you would only have one ready handler, which would do stuff, then trigger the custom event.

So, somewhere else in your code, instead of using $(document).ready, you would use

$(window).bind('setup', function() {
   //code here...
});

And/or

$(window).bind('loaded', function() {
   //some other code here...
});

And in your one and only ready handler, you'd do something like this:

$(document).ready(function() {
   $(window).trigger('setup');
   $(window).trigger('loaded'):
});

$(document).ready() or simply $(function(){}) is just an .addEventListener implementation (well not exactly, but close), meaning you can add listeners before and after.

$(document).ready(listener); // goes off first.
$(document).ready(otherListener); // goes off 2nd.

And so on, it's not hard to sandwich functions. There's no need to hack .ready() imo.

I just had the exact same problem. I put a tiny script on GitHub that adds a $.beforeReady() function. Funny :)

https://github.com/aim12340/jQuery-Before-Ready

Just load the script right after jQuery like in this example:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script src="jquery-before-ready.js"></script>
    </head>
    <body>
        <script>
            $(document).ready({
                alert("This function is declared first!")
            })
        </script>
        <script>
            $.beforeReady(function(){
                alert("This function is declared second but executes first!")
            })
        </script>        
    </body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!