I'm trying to fix an old script written for me. I need it to run without <body onload="init ();">
. I'd like to run the function from inside the script without inline code like that command. Sorry I'm not a JS expert but how do I do this?
标签:
javascript
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
In a pure JavaScript implementation, you'd want to wait for the page to be ready to invoke your events. The simplest solution is like so:
But that's not much better than your original implementation via placing that on the tag itself. What you can do is wait for a specific event though:
This should be fired a little earlier in the cycle and should do nicely.
Additionally, if you are using jQuery, you can simply add a function to be executed when that event is fired using the simple syntax:
Or, if you are using jQuery:
it is not work should be use this
Here's a slight variation on Tejs' response. I often find it more readable and manageable to separate the init() function from the code registering the event handler:
Also, in place of an explicit init() function, I've sometimes used a self-executing anonymous function placed at the very, very bottom of the page, just before the
</body>
tag:best option is to just put the call to
init()
at the bottom of the page:By placing it at the bottom like that, you'll be sure that it runs as pretty much the very last thing on the page. However, note that it's not as reliable as using the onload option in the body tag, or jquery's
$('document').ready()
or mootool'swindow.addEvent('domready', ...)
.