[英]Alternative for using body onload
我是一个新手,我正在玩试图用javascript实现一些东西。
我有一个功能,我需要在我的页面加载后生效,但我不想使用<body onload="init()"
还有另一种选择吗?
<script type="text/javascript">
function init() {
container = document.createElement('div');
<script>
<body onload="init()">
</body>
从load
处理程序调用它:
function init() {
container = document.createElement('div');
// ...
}
window.addEventListener("load", init);
你也可以这样做:
window.onload = function() {
init();
}
好吧,你可以使用jquery,但是你必须把它包含在你的头脑中或者用它
<!-- Google CDN -->
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
如果你想使用谷歌CDN,或
<!-- Microsoft CDN -->
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
</head>
对于Microsoft CDN。 现在,您可以在网页中使用jquery。 所以写下你的头脑
<script type="text/javascript">
$(window).on('load",function(){
// your code
});
</script>
当然,您需要知道如何使用jquery来使用此解决方案。 但是,你也可以使用javasript,但我建议你开始学习jquery:非常有用。
<script>
window.onload = function() {
//your code
}
</script>
这应该是正确的方式;)
非常重要:在您的文档开始加载时调用此函数! 如果你想在页面加载结束时应用一些东西(更好的解决方案,以提高加载速度)使用
$(document).ready(function(){
//your code
});
在jquery,或
document.addEventListener("DOMContentLoaded", function(event) {
//your code
});
在javascript中
我是编程新手但我认为你可以这样做:用Jquery
$(document).ready(function(){
// code loaded..
});
没有Jquery
// this code is bad to practise
<script type="text/javascript">
function init() {
// Put your code here
}
window.onload = init;
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.