Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for using body onload

I'm a newbie and i'm playing around trying to achieve something using javascript.

I have a function which i need to take effect once my page loads but i don't want to use <body onload="init()" is there another alternative?

            <script type="text/javascript">
            function init() {
            container = document.createElement('div');
            <script>

            <body onload="init()">

            </body>
like image 745
Chima Avatar asked Nov 20 '15 19:11

Chima


People also ask

Does onload only work on body?

onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well (see "Supported HTML tags" below).

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?

In HTML, the onload attribute is generally used with the <body> element to execute a script once the content (including CSS files, images, scripts, etc.) of the webpage is completely loaded. It is not necessary to use it only with <body> tag, as it can be used with other HTML elements.

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

The window's load event For the window object, the load event is fired when the whole webpage (HTML) has loaded fully, including all dependent resources, including JavaScript files, CSS files, and images. It's a good practice to use the addEventListener() method to assign the onload event handler whenever possible.


2 Answers

Call it from a load handler:

function init() {
  container = document.createElement('div');

  // ...
}

window.addEventListener("load", init);
like image 200
Paul Roub Avatar answered Nov 02 '22 15:11

Paul Roub


You can also do:

window.onload = function() {
 init();
}
like image 2
defau1t Avatar answered Nov 02 '22 15:11

defau1t