hhh hhh - 2 months ago 91
Javascript Question

Wait for document ready in ES6 modules

With hoisting, ES6 modules are loaded before the document is ready.

For example,

// module.js
console.log('body', document.body);
export let a = 1;

// main.js
import {a} from 'module'


log
body null
in the console.

How to have ES6 modules that use DOM manipulation and required
document ready
?

I tried to use

$(document).ready(function() {
var a = 1;
});

export {a};


in my module but babel returned me an
Unexpected token
error.

I also tried

$(document).ready(function() {
export let a = 1;
});


and I had an
'import' and 'export' may only appear at the top level
error.

Update:

I have the same problem with

document.addEventListener("DOMContentLoaded",function(){
var a = 1;
}

export {a};


because
a
is not defined.

that is to say the variable to export are not available (see my update).

Answer

Try to place your <script> tag at the bottom of <body/>. By doing this, document.body will be available and it won't throw an error.

Comments