Javascript 如何在页面加载时运行函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4842590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run a function when the page is loaded?
提问by Claes Gustavsson
I want to run a function when the page is loaded, but I don't want to use it in the <body>
tag.
我想在页面加载时运行一个函数,但我不想在<body>
标签中使用它。
I have a script that runs if I initialise it in the <body>
, like this:
如果我在 中初始化它,我有一个脚本可以运行<body>
,如下所示:
function codeAddress() {
// code
}
<body onLoad="codeAddress()">
But I want to run it without the <body onload="codeAddress()">
and I have tried a lot of things, e.g. this:
但是我想在没有 的情况下运行它<body onload="codeAddress()">
并且我尝试了很多东西,例如:
window.onload = codeAddress;
But it is not working.
但它不起作用。
So how do I run it when the page is loaded?
那么如何在页面加载时运行它呢?
回答by Darin Dimitrov
window.onload = codeAddress;
should work - here's a demo, and the full code:
window.onload = codeAddress;
应该可以工作 -这是一个演示,以及完整的代码:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
</script>
</head>
<body onload="codeAddress();">
</body>
</html>
回答by Spencer May
Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.
自 jQuery 发布以来,原生 JavaScript 并没有使用 jQuery 或 window.onload,而是采用了一些很棒的功能。所有现代浏览器现在都拥有自己的 DOM 就绪函数,无需使用 jQuery 库。
I'd recommend this if you use native Javascript.
如果您使用本机 Javascript,我会推荐这个。
document.addEventListener('DOMContentLoaded', function() {
alert("Ready!");
}, false);
回答by Eat at Joes
Taking Darin's answer but jQuery style. (I know the user asked for javascript).
采用 Darin 的答案,但采用 jQuery 风格。(我知道用户要求使用 javascript)。
$(document).ready ( function(){
alert('ok');
});?
回答by Habeeb
Alternate solution. I prefer this for the brevity and code simplicity.
替代解决方案。为了简洁和代码简单,我更喜欢这个。
(function () {
alert("I am here");
})();
This is an anonymous function, where the name is not specified. What happens here is that, the function is defined and executed together. Add this to the beginning or end of the body, depending on if it is to be executed before loading the page or soon after all the HTML elements are loaded.
这是一个匿名函数,未指定名称。这里发生的是,函数是一起定义和执行的。将此添加到正文的开头或结尾,具体取决于它是在加载页面之前还是在所有 HTML 元素加载后不久执行。
回答by Will
window.onload = function() {
... etc. is not a great answer.
window.onload = function() {
...等不是一个很好的答案。
This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours. So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.
这可能会起作用,但它也会破坏已经与该事件挂钩的任何其他函数。或者,如果另一个函数在您的事件之后挂接到该事件,它将破坏您的事件。因此,您可能会在之后花费大量时间试图弄清楚为什么原来的工作不再有效。
A more robust answer here:
if(window.attachEvent) {
window.attachEvent('onload', yourFunctionName);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
yourFunctionName(evt);
};
window.onload = newonload;
} else {
window.onload = yourFunctionName;
}
}
Some code I have been using, I forget where I found it to give the author credit.
我一直在使用的一些代码,我忘记了在哪里找到它来给作者信用。
function my_function() {
// whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}
Hope this helps :)
希望这可以帮助 :)
回答by Kamil Kie?czewski
Try readystatechange
尝试就绪状态更改
document.addEventListener('readystatechange', () => {
if (document.readyState == 'complete') codeAddress();
});
where states are:
状态是:
- loading- the document is loading (no fired in snippet)
- interactive- the document is parsed, fired before
DOMContentLoaded
- complete- the document and resources are loaded, fired before
window.onload
- 加载- 文档正在加载(在代码段中没有触发)
- 交互式- 文档被解析,之前被触发
DOMContentLoaded
- 完成- 文档和资源被加载,之前被触发
window.onload
<script>
document.addEventListener("DOMContentLoaded", () => {
mydiv.innerHTML += `DOMContentLoaded (timestamp: ${Date.now()})</br>`;
});
window.onload = () => {
mydiv.innerHTML += `window.onload (timestamp: ${Date.now()}) </br>` ;
} ;
document.addEventListener('readystatechange', () => {
mydiv.innerHTML += `ReadyState: ${document.readyState} (timestamp: ${Date.now()})</br>`;
if (document.readyState == 'complete') codeAddress();
});
function codeAddress() {
mydiv.style.color = 'red';
}
</script>
<div id='mydiv'></div>
回答by Russ Cam
Take a look at the domReady scriptthat allows setting up of multiple functions to execute when the DOM has loaded. It's basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.
查看domReady 脚本,该脚本允许设置多个函数以在 DOM 加载时执行。它基本上是 Dom ready 在许多流行的 JavaScript 库中所做的,但它是轻量级的,可以在外部脚本文件的开头使用和添加。
Example usage
示例用法
// add reference to domReady script or place
// contents of script before here
function codeAddress() {
}
domReady(codeAddress);
回答by Rudra
window.onload will work like this:
window.onload 将像这样工作:
function codeAddress() {
document.getElementById("test").innerHTML=Date();
}
window.onload = codeAddress;
<!DOCTYPE html>
<html>
<head>
<title>learning java script</title>
<script src="custom.js"></script>
</head>
<body>
<p id="test"></p>
<li>abcd</li>
</body>
</html>