如何在页面加载时调用 JavaScript 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3842614/
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 do I call a JavaScript function on page load?
提问by palAlaa
Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload
attribute to the body containing a bit of JavaScript (usually only calling a function)
传统上,要在页面加载后调用 JavaScript 函数,您onload
需要向包含一些 JavaScript 的正文添加一个属性(通常只调用一个函数)
<body onload="foo()">
When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload
attribute since I'm using JSP fragments, which have no body
element I can add an attribute to.
页面加载完毕后,我想运行一些 JavaScript 代码,用来自服务器的数据动态填充页面的各个部分。我无法使用该onload
属性,因为我使用的是 JSP 片段,这些片段没有body
可以添加属性的元素。
Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.
有没有其他方法可以在加载时调用 JavaScript 函数?我宁愿不使用 jQuery,因为我对它不是很熟悉。
回答by Matt Sieker
If you want the onload method to take parameters, you can do something similar to this:
如果你想让 onload 方法带参数,你可以做类似这样的事情:
window.onload = function() {
yourFunction(param1, param2);
};
This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.
这将 onload 绑定到一个匿名函数,当调用该函数时,将使用您提供的任何参数运行您想要的函数。而且,当然,您可以从匿名函数内部运行多个函数。
回答by Ahmed Jolani
Another way to do this is by using event listeners, here how you use them:
另一种方法是使用事件侦听器,这里是如何使用它们:
document.addEventListener("DOMContentLoaded", function() {
you_function(...);
});
Explanation:
解释:
DOMContentLoadedIt means when the DOM Objects of the document are fully loaded and seen by JavaScript, also this could have been "click", "focus"...
DOMContentLoaded这意味着当文档的 DOM 对象完全加载并被 JavaScript 看到时,这也可能是“点击”、“焦点”...
function()Anonymous function, will be invoked when the event occurs.
function()匿名函数,会在事件发生时调用。
回答by STW
Your original question was unclear, assuming Kevin's edit/interpretation is correct then this first option doesn't apply
您最初的问题不清楚,假设凯文的编辑/解释是正确的,那么第一个选项不适用
The typical options is using the onload
event:
典型的选项是使用onload
事件:
<body onload="javascript:SomeFunction()">
....
You can also place your javascript at the very end of the body; it won't start executing until the doc is complete.
你也可以把你的 javascript 放在 body 的最后;在文档完成之前它不会开始执行。
<body>
...
<script type="text/javascript">
SomeFunction();
</script>
</body>
And, another options, is to consider using a JS framework which intrinsically does this:
而且,另一种选择是考虑使用本质上执行此操作的 JS 框架:
// jQuery
$(document).ready( function () {
SomeFunction();
});
回答by Sarfraz
function yourfunction() { /* do stuff on page load */ }
window.onload = yourfunction;
Or with jQuery if you want:
或者如果需要,可以使用 jQuery:
$(function(){
yourfunction();
});
If you want to call more than one function on page load, take a look at this article for more information:
如果您想在页面加载时调用多个函数,请查看这篇文章以获取更多信息:
回答by anonymous
<!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>
回答by Amir Md Amiruzzaman
You have to call the function you want to be called on load (i.e., load of the document/page). For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.
您必须调用要在加载时调用的函数(即加载文档/页面)。例如,您要在文档或页面加载时加载的函数称为“yourFunction”。这可以通过调用文档的加载事件函数来完成。请参阅下面的代码以获取更多详细信息。
Try the code below:
试试下面的代码:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
yourFunction();
});
function yourFunction(){
//some code
}
</script>
回答by Abhishek
here's the trick (works everywhere):
这是诀窍(适用于任何地方):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
回答by Kamil Kie?czewski
For detect loaded html (from server) inserted into DOM use MutationObserver
or detect moment in your loadContent function when data are ready to use
用于检测插入到 DOM 中的已加载 html(来自服务器)MutationObserver
或在数据准备好使用时检测 loadContent 函数中的时刻
let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });
// TEST: simulate element loading
let tmp=1;
function loadContent(name) {
setTimeout(()=>{
console.log(`Element ${name} loaded`)
content.innerHTML += `<div>My name is ${name}</div>`;
},1500*tmp++)
};
loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>