• Resolved mikeldev

    (@mikeldev)


    Hi,

    I would like to know what is the script handle of the autoptimize_.js script.

    I need to add PHP data to JS and the way to do it is with wp_localize_script

    <?php wp_localize_script( $handle, $name, $data ); ?>

    $handle
    (string) (required) The registered script handle you are attaching the data for.
    Default: None

    Because Autoptimize join all my scripts I can’t use their handle name.
    To avoid this issue now I am adding an empty script (excluded in Autoptimize settings), just because I know the name.
    This is not ideal as it does a unnecessary request.

    
    // This empty script is needed because wp_localize_script need a script handle name.
    // Because the scripts will be concat by Autoptimeze we can't know that name
    wp_enqueue_script('global-script', get_template_directory_uri() . '/js/global.js', array(), null, true);
    
    $phpData = array(
    	'contactForm' => array(
    		'key' => get_field('contact_form_mandrill_key', 'option'),
    		// ...
    	)
    );
    wp_localize_script('global-script', 'phpData', $phpData);
    
Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Optimizing Matters

    (@optimizingmatters)

    hey @mikeldev;
    AO doesn’t use script (or style) handles; it is active after wordpress finished parsing the queue and injected all scripts (both linked and localized).

    as such you should be able to continue as you would without changing you logic. if you have “also aggregate inline JS” active, the localized script will also be optimized (i.e. removed from HTML and added to the autoptimize_xyz.js file), if you don’t have that option active it will remain in the HTML.

    hope this clarifies,
    frank

    Thread Starter mikeldev

    (@mikeldev)

    Thanks.

    The alternative I found is to add hidden input elements with the value injected by PHP.

    Plugin Author Optimizing Matters

    (@optimizingmatters)

    great to see you found a solution, but could you (to satisfy my own curiosity) explain what the problem was (as based on my experience wp_localized_scripts work without anything special needing to be done)?

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Support for wp_localize_script(). Inject PHP data in JS’ is closed to new replies.