如何在 BODY onload 事件中使用它之前先加载外部 javascript 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25331883/
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 load external javascript file first before using it in BODY onload event?
提问by Bubba Yakoza
<head>
<script type="text/javascript" src="folder/externaljs.js">
</head>
<body onload="someFunctionInExternalJS();">
</body>
How do I ensure that externaljs.jsis loaded first so that someFunctionInExternalJS()
is executed as a result? Thanks!
我如何确保首先加载externaljs.js以便someFunctionInExternalJS()
作为结果执行?谢谢!
回答by Blake A. Nichols
The external javascript file will load and execute before continuing along and building the DOM, unless it is async (http://www.w3schools.com/tags/att_script_async.asp).
外部 javascript 文件将在继续构建 DOM 之前加载和执行,除非它是异步的 ( http://www.w3schools.com/tags/att_script_async.asp)。
Any external file that the DOM requires to build (javascript, css primarily) will load as it is being parsed. This is why you will sometimes see javascript at the bottom of the body tag instead of the head.
DOM 需要构建的任何外部文件(主要是 javascript、css)都将在解析时加载。这就是为什么你有时会在 body 标签的底部而不是头部看到 javascript。
回答by Paulo
using jquery,
使用jQuery,
$(document).ready(function() {
//anything in here will only be called/work when the document is ready.
//call your function in here, instead of bodyonload
});
回答by Lo?c Poullain
I tested this code and it works fine :
我测试了这段代码,它工作正常:
<!doctype html>
<html>
<head>
<script src="my_script.js"></script>
</head>
<body onload="my_function()">
</body>
</html>
with this in my_script.js :
在 my_script.js 中使用这个:
function my_function () {
alert("Hello world!");
}
Another solution is to write this in my_script.js :
另一个解决方案是在 my_script.js 中编写:
function my_function () {
alert("Hello world!");
}
document.onload = my_function();