Automatically executes a method's js code after the page loads

  • 2020-03-30 03:53:26
  • OfStack

1. Onload in body:


<body onload="myfunction()">

2. Window.onload:


<script type="text/javascript">
function myfun()
{
alert("this window.onload");
}

window.onload=myfun;//Don't bracket
</script>

The following example changes the background color of id_1 after the page finishes loading.


<script language="javascript" >
function myfun() {
document.getElementById("id_1").style.background= "#000"; //Change the background color
}
//The js implementation automatically executes a method after a page is loaded

window.onload=myfun;//Don't bracket
</script>

Related articles: