如何在加载页面后加载jQuery代码
方法1:使用加载事件的on()方法: jQuery中的on()方法是用来将任何事件的处理程序附加到所选元素上的。首先使用选择器选择窗口对象,然后在这个元素上使用on()方法。
每当整个页面完成加载,包括其他资源如样式表和图片,”加载 “事件就会发生。这个事件被检查以绕过它到on()方法中。然后可以在这个方法的第二个参数中调用要执行的函数。现在,这将在页面完成加载后调用该函数。
语法:
$(window).on('load', functionTobeLoaded() )
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to load jQuery code
after page loading?
</title>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to load jQuery code
after page loading?
</b>
<p>
The current datetime is:
<span class="date"></span>
</p>
<script type="text/javascript">
$(window).on('load', showDatetime());
function showDatetime() {
document.querySelector(".date").textContent
= new Date();
}
</script>
</body>
</html>
输出:页面加载后。
方法2:使用ready()方法: jQuery中的ready()方法是用来在DOM可以被安全操作的时候执行代码。它接受一个处理程序,可以与需要执行的函数一起传递。现在它将在页面完成加载后调用该函数。
语法:
$(document).ready( functionTobeLoaded() )
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to load jQuery code
after page loading?
</title>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to load jQuery code
after page loading?
</b>
<p>
The current datetime is:
<span class="date"></span>
</p>
<script type="text/javascript">
$(document).ready(
showDatetime()
);
function showDatetime() {
document.querySelector(".date").textContent
= new Date();
}
</script>
</body>
</html>
输出:页面加载后