Asset loading with gulp.js or Grunt

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?

3 Answers
3

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.

function enqueue_scripts() {
    // These files are concatenated into plugins.min.js
    wp_register_script( 'fancybox', false );
    wp_register_script( 'flexslider', false );

    // Concatenated js files
    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', 1 );

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.

Leave a Comment