This article shares common methods for automatically executing JS functions on web pages for your reference. The specific content is as follows
1. JS method
1. The simplest way to call is to write directly into the body tag of html:
<body onload="myfunction()"> <html> <body onload="func1();func2();func3();"> </body> </html>
2. Call in JS statement:
<script type="text/javascript"> function myfun() { alert("this window.onload"); } /*用window.onload调用myfun()*/ window.onload = myfun;//不要括号 </script>
Third type
<script type="text/javascript"> window.onload=function(){ func1(); func2(); func3(); } </script>
2. JQ method
1. Execute after all documents of the entire page are loaded. Unfortunately, this method not only requires that the DOM tree of the page be fully loaded, but also requires that all external images and resources be loaded. What's even more unfortunate is that if external resources, such as images, take a long time to load, then the execution of this js method will feel slower. In other words, this is the most rigorous method of executing the method after the page is loaded.
window.onload =function() { $("table tr:nth-child(even)").addClass("even"); //This is jquery code};
2. Just load all the DOM structures and execute the method before the browser puts all the HTML into the DOM tree. Included before loading external images and resources.
$(document).ready(function() { $("table tr:nth-child(even)").addClass("even"); //Any js special effects that need to be executed});
There is also an abbreviation
$(function() { $("table tr:nth-child(even)").addClass("even"); //Any js special effects that need to be executed });
Three common methods for automatically executing JS functions on web pages
In the Head area in HTML, there are the following functions:
<SCRIPT LANGUAGE="JavaScript"> functionn MyAutoRun() { //以下是您的函数的代码,请自行修改先! alert("函数自动执行哦!"); } </SCRIPT>
Next, we will focus on the above function and let it run automatically when the web page is loaded!
①The first method
Change the above code to:
<SCRIPT LANGUAGE="JavaScript"> functionn MyAutoRun() { //以下是您的函数的代码,请自行修改先! alert("函数自动执行哦!"); } window.onload=MyAutoRun(); //仅需要加这一句 </SCRIPT>
②Second method
Modify the Body of the web page to:
Or change to:
③The third method
Use JS timer to execute functions intermittently:
setTimeout("MyAutoRun()",1000); //Execute the MyAutoRun() function every 1000 milliseconds
The implementation method is to change the top JS function to:
<SCRIPT LANGUAGE="JavaScript"> functionn MyAutoRun() { //以下是您的函数的代码,请自行修改先! alert("函数自动执行哦!"); } setTimeout("MyAutoRun()",1000); //这样就行拉 </SCRIPT>
Other methods are more special, not commonly used, and not very versatile, so I won’t introduce them!
The above introduces to you the common methods of automatic execution of JS functions. I hope it will be helpful to your learning.