hhh hhh - 1 year ago 441
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'

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

I also tried

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

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


I have the same problem with

var a = 1;

export {a};

is not defined.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download