I saw some jquery code on the Net somewhere, that took this form :
<script>
function doSomething(message)
{
$(document).ready(function(){
alert(message);
});
};
</script>
i.e. an external function ("doSomething") which has $(document).ready inside it. I'm confused because isn't the code under $(document).ready triggered when the DOM is loaded ? Its like having an event handler inside a function (?). Does this form of code make sense to anyone ? Thanks.
It makes sense. $(document).ready registers an event handler that is fired when the DOM is fully loaded. The anonymous function that is passed to it, is that handler. If you register that handler after the DOM is loaded, it is fired immediately.
Javascript can be executed before the DOM is fully loaded, so what this function does, it actually registers messages that are not to be shown before the DOM is loaded. You can use this construct if you don't want the message to be displayed before the DOM is fully loaded.
It was probably an error on the part of the original coder. You could do that, but you'd want to call doSomething
pretty early on. Note that if the DOM is already ready when you call ready
, jQuery will call the code, so it will happen either way, but it won't happen until someone, somewhere, calls doSomething
. I can't see much purpose to the pattern, so unless you have some strong argument for using it — and given the question, I suspect you don't :-) — you can safely ignore it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With