Customizer: When to use customize_preview_init VS customize_controls_enqueue_scripts

As the names themselves seem to state, one of those hooks to the customize-controls, the other to the customize-preview. They are not the same and you could in fact use them both, for different purposes.

  • If you’re hooking in JS code to affect the controls in the customizer, then you would want to use customize_controls_enqueue_scripts.

  • If you’re hooking in JS code to be in the preview frame and possibly to receive events from the controls via postMessage, and thus able to dynamically change the contents of the preview frame rapidly, you would use customize_preview_init.

Twenty Fourteen actually uses them both. The first one is used to add a featured-content-suggest script to the custom controls in the customizer. The second is used for all the postMessage code in the preview frame.

Specifically, the customize_preview_init hook is fired from the wp_loaded action when the customizer is_preview() returns true and is_admin() returns false… so only in the preview window, not on the admin side of things… which is where you want to enqueue scripts that adjust the preview frame only.

Leave a Comment