Reputation: 48
I import modules like that:
<script type="module">
import mod_test from '../classes/mod_test.js';
window.mod_test= mod_test;
</script>
But Chrome says sometimes if i call a function window.mod_test.test();
cannot read property 'test' of undefined
which is called in a Jquery synchronous request.
What am i doing wrong? Or it is a bug with chrome, because it happens only sometimes?
The module looks like that
var mod_test = {
a: null,
test: function (b) {
this.a=b;
}
};
export default mod_test;
Upvotes: 0
Views: 73
Reputation: 20744
Since you have no CORS issue, I think that the problem could be in a race condition between module loading and module exported fuction calling. To be sure you may try following approach. Define the app runner before the module loader:
<script>
window.runTheApp = function(mod_test) {
mod_test.test();
// ...
}
</script>
and then load your module with the app runner call:
<script type="module">
import mod_test from '../classes/mod_test.js';
window.runTheApp(mod_test);
</script>
Also, the dynamic import could be useful. For me it makes the approach more clear:
<script type="module">
import('../classes/mod_test.js')
.then(function(module) {
console.log('module loaded');
window.runTheApp(module.default);
})
</script>
Upvotes: 2