JS execution on page loading without using jQuery

So, I know that if you use jQuery, you can use $(document).load(function(){}); so that any code you write to the function runs after the entire page loads, but is there a way to do something like this if you are not using jQuery and just using JS?

For instance...

 <html> <head> <script type="text/javascript"> var box = document.getElementById('box'); alert(box); </script> </head> <body> <div id="box" style="width:200px; height:200px; background-color:#999; margin:20px;"></div> </body> </html> 

If I use this method, the warning just says null . So, is there a way to make js code run after the page loads?

+6
source share
4 answers

I use:

 <script type="text/javascript"> window.onload = function(){ //do stuff here }; </script> 

This way you do not need to use any onload tags in your html.

+13
source

The easiest way is to simply put your script at the end of the document, usually before the closing tag:

 <html> <head> </head> <body> <div id="box" style="width:200px; height:200px; background-color:#999; margin:20px;"></div> <script type="text/javascript"> var box = document.getElementById('box'); alert(box); </script> </body> </html> 
+8
source

You can use various methods for this.

The easiest and easiest way is to simply add a script tag to the end of the body tag:

 <html> <head> <title> Example </title> </head> <body> <div> <p>Hello</p> </div> <script type="text/javascript"> // Do stuff here </script> </body> </html> 

The jQuery method does something similar to:

 window.onload = function() { // Do stuff here } 

Usually I just do it the second way, just in case.

To ensure compatibility with multiple browsers, go through the jQuery source and find what they use.

+4
source

You can use onload in the body tag.

 <head> <script type="text/javascript"> function doSomething() { //your code here } </script> </head> <body onload="doSomething()"> 
+2
source

Source: https://habr.com/ru/post/945844/


All Articles