简体   繁体   English

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

[英]How to correctly execte function from external file onload?

I have a function myModule.myFunction in a larger external script mymodule.js that is executed on load . 我在较大的外部脚本mymodule.js中有一个函数myModule.myFunction ,该脚本在load执行。 Everything seems to work fine. 一切似乎都正常。 But now I have added 但是现在我添加了

"use strict";

at the top of the external script. 在外部脚本的顶部。 And I get a 我得到一个

TypeError: MyModule is undefined

and the page stops working. 并且页面停止工作。 So I am wondering where I did something problematic. 所以我想知道我在哪里做了有问题的事情。 Here is the structure of my page (unfortunately, I did not manage to produce a minimal example): 这是页面的结构(不幸的是,我没有产生一个最小的示例):

<!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>

Here is what the MyModule in mymodule.js looks like: 这是mymodule.jsMyModule的样子:

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

In myModule.js you need to explicitly assign myModule to the window object (when using "use strict"). myModule.js您需要将myModule显式分配给window对象(使用“ use strict”时)。

Change it to window.myModule = ... 将其更改为window.myModule = ...

Reason: in sloppy mode, undeclared variables are automatically added as properties on the global object. 原因:在草率模式下,未声明的变量会作为属性自动添加到全局对象上。 In strict mode they are not )to avoid accidental interference). 在严格模式下,它们不是为了避免意外干扰)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM