我正在页面中动态加载我的JavaScript文件:
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script'),
script3 = document.createElement('script');
script1.type = 'text/javascript';
script1.src = 'myScript1.js';
script2.type = 'text/javascript';
script2.src = 'myScript2.js';
script3.type = 'text/javascript';
script3.src = 'myScript3.js';
document.body.appendChild(script1);
document.body.appendChild(script2);
document.body.appendChild(script3);
}
</script>
</head>
<body>
</body>
</html>
我需要知道这些Scripts何时完全加载。是否有任何解决方法或代码片段可以执行此操作?
答案 0 :(得分:1)
显然你会想做“有用的东西”,而不是简单的console.log,我已经展示了 但是......这并不总是可行的 试试这个 然后,你的代码 在每个脚本的末尾添加类似scrimpt1.addEventListener('load', function() { console.log('loaded'); });
var numScripts;
function scriptLoaded() {
numScripts --;
if(numScripts == 0) {
console.log('huzzah all scripts loaded');
}
}
window.onload = function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script'),
script3 = document.createElement('script');
numScripts = 3;
script1.type = 'text/javascript';
script1.src = 'myScript1.js';
script2.type = 'text/javascript';
script2.src = 'myScript2.js';
script3.type = 'text/javascript';
script3.src = 'myScript3.js';
document.body.appendChild(script1);
document.body.appendChild(script2);
document.body.appendChild(script3);
}
if(windows.scriptLoaded) {
scriptLoaded();
}
答案 1 :(得分:0)
function greetFinished() {
alert("Do stuff finished");
}
function greet (greeting, callback) {
alert(greeting)
callback (options);
}
greet("Hello",greetFinished);
greetFinished将在greet函数内部调用greetFinished是一个回调函数,它将在警报后调用。