How to do $( document ).ready() with webpack and babel?

28 Views Asked by At

I build with webpack and transpile with babel. The pages are generated in php. Once the js bundles are loaded, I want to mount a React component.

I have been using jQuery for this, but it seems wrong to me, and I guess there is a better way. Could you help me with this?

Here's how it works now:

import $ from "jquery";

const documentReadyPromise = Symbol('documentReadyPromise');

window[documentReadyPromise] = new Promise(function(resolve) {
    $(() => {
        resolve();
    });
});

export function getDocumentReadyPromise() {
    return window[documentReadyPromise];
}

/**
 * Gets a promise that gets resolved as soon as React can be used
 *
 * @returns {Promise}
 */
export function getReactReadyPromise() {

    // React can be used as soon as:
    return Promise.all([

        // a) document is ready
        window[documentReadyPromise]

        // AND b) .... etc - add more entries here
    ]);
}

And then I use it like this:

getReactReadyPromise().then(() => {
    ReactDOM.render(
        <MyComponent />,
        document.getElementById('my-component-mount-point')
    );
});
0

There are 0 best solutions below