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

前端 未结 3 1369
别那么骄傲
别那么骄傲 2021-02-20 03:40

I\'ve attached multiple functions in multiple files to $(document).ready and would like to attach a single function to happen before them as either the first that $(document).re

相关标签:
3条回答
  • 2021-02-20 04:29

    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>
    
    0 讨论(0)
  • 2021-02-20 04:33

    $(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.

    0 讨论(0)
  • 2021-02-20 04:34

    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'):
    });
    
    0 讨论(0)
提交回复
热议问题