When you want to run some code right after the Block Editor / Gutenberg initializes, the documentation provides little to no clues on how to do this.
Here are 2 ways you can run your code right after the Block Editor initializes.
Method 1
The block editor calls initializeEditor
to start the editor and stores the returned Promise
in window._wpLoadBlockEditor
. We can use that to put our logic that we want to run right after the editor starts.
Method 2
This method takes advantage of the registerPlugin
method provided by the Block Editor.
We register our own plugin, and then the code is ran once and render nothing.
I’m not too sure about whether this would run once since technically the plugin is a Component, so it might get reused / rerun somehow. so I added a useEffect
method to make sure it’s only called once.
2 replies on “How to Run Code When the Block Editor Initializes (Gutenberg)”
Thanks Benjamin, nice tip! And how about the front-end? Should we use domReady method too?
Yes, that’s definitely a good idea to ensure the rest of the page loads first before running your JS