boxybird / inertia-wordpress

The WordPress adapter for Inertia.js.
170 stars 26 forks source link

DOMContentLoaded eventListener is needed for createInertiaApp to work #11

Closed Tanguy-Plf closed 3 years ago

Tanguy-Plf commented 3 years ago

Hi there,

I did install the plugin to create a wordpress theme using inertia, react and typescript but I was facing an issue with inertia that couldn't get the "app" element. I don't know why but placing the createInertiaApp() function in an event listener fixed it.

The problem is that the element with id 'app' doesn't exist when the function is called in app.js which is strange because it looks like it work in your theme exemple using vuejs. I never used laravel-mix before so it might be the reason it fails.

Here is a repository to see the problem : https://github.com/Tanguy-Plf/wordpress-inertia you'll need to install the polylang plugin and go to http://localhost:10018/es/ to see the bug in the console. The fix is commented bellow in app.tsx

Thank you for your help!

boxybird commented 3 years ago

Hello!

Have a guess as to what's going on. Looking at your wp_enqueue_scripts callback, I notice you're loading the app.js file in the <head> rather than in the footer. Which makes sense as to why you're needing to use the "DOMContentLoaded" listener.

https://github.com/Tanguy-Plf/wordpress-inertia/blob/abff405f6054cd3c851207994e8905360df9acd4/web/app/themes/OS-theme/core/inertia.php#L11

Try adding the script to the footer instead:

 wp_enqueue_script('bb_inertia', get_stylesheet_directory_uri() . '/dist/js/app.js', [], false, true);

Let me know if that does the trick!

Tanguy-Plf commented 3 years ago

Hello,

Yep that was the problem. That's why I should think before copy pasting 😢 .

thanks for your time,

boxybird commented 3 years ago

No problem at all!