Search code examples
javascriptonloadstrict

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. 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:

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

Solution

  • In myModule.js you need to explicitly assign myModule to the window object (when using "use strict").

    Change it to 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).