gpt4 book ai didi

javascript - HTML:动态 JavaScript 完全加载后

转载 作者:行者123 更新时间:2023-12-03 09:35:17 24 4
gpt4 key购买 nike

我正在页面中动态加载 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>

我需要知道这些脚本何时完全加载。是否有任何解决方法或代码片段可以做到这一点?

最佳答案

之前 document.body.appendChild

scrimpt1.addEventListener('load', function() { console.log('loaded'); });

显然你会想要做“一些有用的事情”而不是我展示的简单的console.log

但是......这并不总是可行的

试试这个

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();
}

关于javascript - HTML:动态 JavaScript 完全加载后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31355663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com