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
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>
$(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.
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'):
});