Customizer: When to use customize_preview_init VS customize_controls_enqueue_scripts

There appears to be some conflicts between the codex and the twentyfourteen theme code with respect to which action to hook to load your live preview .js (ex: customizer.js)

In the twentyfourteen theme, the live preview handler, customizer.js, is loaded using customize_preview_init:

Read More
function twentyfourteen_customize_preview_js() {
    wp_enqueue_script( 'twentyfourteen_customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '20131205', true );
}
add_action( 'customize_preview_init', 'twentyfourteen_customize_preview_js' );

However, in the codex, and in this answer, we are advising to use customize_controls_enqueue_scripts

3 – Create an action hooked to ‘customize_controls_enqueue_scripts’
that enqueues the js file

When I enqueue using that method, the .js is attached to the parent DOM (the customizer controls window itself), not the preview iframe (the “About” document in chrome dev preview) as you can see from the screenshot below.

enter image description here

Related posts

Leave a Reply

1 comment

  1. 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.