Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to <body onload="init ();">

Tags:

javascript

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?

like image 938
firefusion Avatar asked Sep 26 '11 21:09

firefusion


People also ask

Is there any difference between body onload () and document ready () function?

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.

Is onload necessary?

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.

What can be used in place of load event in JavaScript?

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.

What is onload init?

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.


2 Answers

<script type="text/javascript">
    function init() {
        // Put your code here
    }
    window.onload = init;
</script>

Or, if you are using jQuery:

$(function() {
    // Your code here
});
like image 106
Brad Avatar answered Sep 17 '22 12:09

Brad


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();
 });
like image 31
Tejs Avatar answered Sep 19 '22 12:09

Tejs