I just started using gulp.js which is a task runner like Grunt and a lot of the sites I work on are using WordPress so I was wondering if anyone has some ideas about how to use the combined scripts that gulp will output with WordPress (or for that matter any file that combines multiple files into one).
So say I have gulp setup to concatenate and minify a couple vendor plugin files, like fancybox, and flexslider to a file called plugins.min.js
. I would then load that into my theme by using wp_enqueue_script
from the functions.php
file.
function enqueue_scripts() {
wp_register_script( 'custom-plugins', get_template_directory_uri() . '/assets/js/build/plugins.min.js', array( 'jquery' ), '1.0', true );
wp_enqueue_script( 'custom-plugins' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
But say a plugin gets installed that uses fancybox as well (damn clients). Since the script is being loaded as custom-plugins
instead of fancybox
the fancybox.js
file will be loaded from that plugin as well as my minified script file, which could cause issues and unnecessary file size.
Same goes for wp_enqueue_style
. Any thoughts / ideas on this?
I’ve been messing around with it some more and the best way I can think of is to register the scripts that are going to be combined and set their source to false to prevent other plugins from loading them. I know it’s not the best solution and is a little hacky but can’t think of any other ways. Plus this will only work if the handle name is exactly the same.
I also had to add a higher priority on the
wp_enqueue_scripts
action to make sure that it would take precedence over other plugins.This is unsolvable. There are no means of identifying what exactly third party code is loading, short of maintaining some kind of resources database (file checksums for example). Which would be a huge pain and still not completely reliable.
The best one can do in this situation is to use the script in a way that minimizes probability of conflicts. noConflict functionality where implemented and so on.
This is a question that has been answered in several other places.
The summary answer is that if all plugins are properly using wp_enqueue_script then you can write custom code which the first link below outlines (vaguely) that will concatenate & minify the needed JS/CSS or you can use a WordPress plugin to do that.
See WordPress Stack Exchange post: Could the WP script/style loader be used to concatenate and gzip scripts and styles in the front-end?.
Two popular WordPress plugins that can concatenate and minify JS & CSS are,