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?
The main differences between the two are: Body. Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document. ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded.
Yes, there could be unexpected consequences. But, no, it's not absolutely necessary. The timing could be off for things still loading, like complicated layouts, deep DOM structures, dynamic HTML from other scripts, or images. To avoid these situations, it's always safest to wrap your script in an onload event.
Solution(By Examveda Team)DOMContentLoaded and readystatechange are alternatives to the load event: they are triggered sooner, when the document and its elements are ready to manipulate, but before external resources are fully loaded.
onload=init because onload is a method of the window object, so you must always precede it with window. for it to work. By omitting the parentheses when you assign the init function to the onLoad property, the function does not run immediately; instead, it runs when the load event occurs after the page is fully loaded.
<script type="text/javascript">
function init() {
// Put your code here
}
window.onload = init;
</script>
Or, if you are using jQuery:
$(function() {
// Your code here
});
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:
<script type="text/javascript" language="javascript">
window.onload = function()
{
init();
};
</script>
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:
document.addEventListener("DOMContentLoaded", function()
{
init();
}, false);
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:
$(document).ready(function() // or $(function()
{
init();
});
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