开发者

Nicest way to run some JS immediately after an element has loaded?

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" v开发者_JS百科alue="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()).


Since javascript includes are generally blocking (unless you load it async ofcourse), it is always a good idea to put your javascript as low as possible on the page. That way the user won't have to wait for your javascript to load while browsing through the page.

So the question here is, do you really want it to load immediately after that element. Or simply at the bottom of the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜