如何从外部文件onload正确执行功能?

How to correctly execte function from external file onload?

我在更大的外部脚本 mymodule.js 中有一个函数 myModule.myFunction,它在 load 上执行。一切似乎都很好。但是现在我添加了

"use strict";

在外部脚本的顶部。我得到一个

TypeError: MyModule is undefined

页面停止工作。所以我想知道我在哪里做了一些有问题的事情。这是我的页面结构(不幸的是,我没有设法生成一个最小的示例):

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
<body>
    <!-- Some html here -->
    <script src="mymodule.js"></script>
    <script>
        function myOnload() {
            myModule.myFunction();
        }
        window.addEventListener('load', myOnload, false);
    </script>
</body>
</html>

这是 mymodule.js 中的 MyModule 的样子:

var myModule = (function(){
    // stuff
})();

myModule.js 中,您需要将 myModule 显式分配给 window 对象(使用 "use strict" 时)。

改为window.myModule = ...

原因:草率模式下,未声明的变量会自动添加为全局对象的属性。在严格模式下它们不是)以避免意外干扰)。