Let's say you've got some HTML,
<input id="mytextbox" type="text" value="hello world" />
And you want to do some magic on that textbox as soon as it's loaded. Maybe add some kind of widget, or button beside it, whatever. There's 2 ways of doing this that I'm aware of. You can throw some jQuery like this in the <head>
$(function() {
$('#mytextbox').magic();
});
And that'll run once the entire DOM is ready, but what if we want it sooner? As soon the element has loaded?
We can put the JS immediately after the element:
<input id="mytextbox" type="text" value="hello world" />
<script>
$('#mytextbox').magic();
</script>
But that's a bit messier, and why should we have to search the entire DOM for an element ID when we know exactly where it is? onclick
events have a this
argument. Isn't there some way we can do something like this...
<input id="mytextbox" type="text" value="hello world" onload="$(this).magic()" />
? Would be nicest solution IMO, but only the body has an onload
event apparently, and no other event seems suitable. Are we basically left to solution #2 if we want some piece of code to run immediately after an element is loaded?
Actually, your second snippet is the "best" (whatever that means, probably fastest) way to apply some Javascript to an element.
<input id="mytextbox" type="text" value="hello world" />
<script type="text/html">
$('#mytextbox').magic();
</script>
You are not searching the entire DOM here. A call like this directly goes down to
document.getElementById('mytextbox');
which is more or less, just insta-access to the node.
Anyway, a practice like this betrays the idea of unobtrusive Javascript. I wouldn't know a reason why you shouldn't apply some code when the DOMContentLoaded
event fires (which is abstracted away by jQuerys .ready()
).
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