This article mainly introduces in detail three commonly used methods for automatic execution of JS functions in web pages. Interested friends can refer to it
1. JS methods
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>
The 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 a shorthand way
$(function() { $("table tr:nth-child(even)"). addClass("even"); //Any js special effects that need to be executed});
There are 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 appear on the web page Run automatically when loading!
①The first method
Change the above code to:
<SCRIPT LANGUAGE="JavaScript"> functionn MyAutoRun() { //以下是您的函数的代码,请自行修改先! alert("函数自动执行哦!"); } window.onload=MyAutoRun(); //仅需要加这一句 </SCRIPT>
②The second method
Modify the Body of the web page to:
Or change to:
③The third method
Use JS timer to execute the function intermittently:
##setTimeout("MyAutoRun()",1000 ); //Execute the MyAutoRun() function every 1000 milliseconds
Implementation method, change the top JS function to:<SCRIPT LANGUAGE="JavaScript"> functionn MyAutoRun() { //以下是您的函数的代码,请自行修改先! alert("函数自动执行哦!"); } setTimeout("MyAutoRun()",1000); //这样就行拉 </SCRIPT>
The above is the detailed content of Three methods for automatic execution (loading) of JS functions. For more information, please follow other related articles on the PHP Chinese website!