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>
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).
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.
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.
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.
Call it from a load
handler:
function init() {
container = document.createElement('div');
// ...
}
window.addEventListener("load", init);
You can also do:
window.onload = 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