Issue adding plugins to the asset pipeline and wp_localize_script()

As the title hopefully makes clear, I’m having an issue using the “dequeuing plugin assets and adding them to the assets pipeline” technique explained in the screencast where the plugin in question uses wp_localize_script() as part of the function that enqueues the script. Basically, the issue is that when dequeuing the script, the wp_localize_script() call has no script handle to hook into since we’ve removed it.

First, am I totally right about that?
Secondly, if I am, is there any way around it?

Some code to explain my situation in case I haven’t been clear:

In my_cool_plugin.php:

function my_cool_plugin_add_js() {

  wp_enqueue_script('my-cool-plugin-js, 'path-to-script', false);

  wp_localize_script('my-cool-plugin-js', 'my-cool-plugin-vars',
    array(
      'var1' => 'var1',
      'var2' => 'var2
    )
  );
}

In Sage’s extras.php:

function my_prefix_remove_plugin_assets() {
  wp_dequeue_script('my-cool-plugin-js');
}

Then I add the path to ‘my-cool-plugin-js’ file to the vendor property in my manifest.json and rebuild assets. However, the page will now make a call to ‘my-cool-plugin-vars’ which doesn’t exist since a script with the handle ‘my-cool-plugin-js’ doesn’t exist either.

Thanks for grabbing the screencast!

You are right. I don’t think there’s going to be an easy way around that unless you were to manually add the output of the localized script to your own JS.

For what it’s worth, with HTTP/2 adoption it’s not as important to worry about things like extra requests for CSS/JS, although all the performance metrics tools are still gonna complain about it.

Thanks for the prompt reply. On the particular site I’m currently working there’s not a whole load of calls to frontend JS files, so it’s not a huge concern.

For other users who find this topic, the conclusion is that if the plugin uses wp_localize_script() the variables will NOT be available if you dequeue the script, and therefore things will break, so those plugins will have to be left as they are unless you add their output to your JS yourself.

1 Like