As titled!
ready()
specifies that it loads after the DOM has been initialized and is ready for JS execution. However, I'm unsure of how that interacts with the JS itself!
If I have some JavaScript with the general format:
let functocall = () => {
alert("Bad ending!");
};
// ...
$(document).ready(() => {
functocall();
});
// ...
functocall = () => {
console.log("Safe!");
};
(note that the JS is loaded via a <script ... defer>
in the head)
In this example, would it ever be possible for the document's ready function to be called and result in the alert()
being called? On the examples I've tried, and the code I'm actually running, it never does, but I'm unsure if there's some edge case where it'd occur due to how the timing lines up.
I'd prefer it this way due to the following constraints:
functocall
cannot be initialized with the other values- The
ready()
call being above the update is for code organization purposes (i.e. the lower section is a long chunk of code, and would be messy above theready()
) - This JavaScript file is loaded with
defer
, to allow the libraries to load in first
I'd imagine I could just put the ready()
into a function, and then call it and pass in the function, but I just personally think it'd look a bit worse that way, so I wanted to see if this was possible instead.
CodePudding user response:
No. We don't know when the whole code is executed. It could be loaded after the document is ready, so the ready
promise is resolved and the code will execute immediately.