HTML:动态 JavaScript 完全加载后

HTML: After Dynamic JavaScripts Loaded Completely

我正在页面中动态加载我的 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'); });

显然你会想做 "something useful" 而不是我展示的简单 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();
}

使用回调

function greetFinished() {
  alert("Do stuff finished");
}

​function greet (greeting, callback) {
  alert(greeting)
  callback (options);
}

greet("Hello",greetFinished);

greetFinished 将在 greet 函数中调用 greetFinished 是一个回调,它将在警报后调用。