8

I'm loading a JavaScript file using wp_enqueue_script into my theme. However, along with it, I'm loading several jQuery files as well, as dependencies for the enqueued script (which has already been concatenated and minified by Grunt). Here is my code:

add_action('wp_enqueue_scripts', function() {
    wp_enqueue_script( 'customscripts', get_template_directory_uri() . '/assets/js/main.min.js', array('jquery', 'jquery-form', 'json2', 'jquery-ui-autocomplete'), NULL, true );
});

For the dependencies array, how would I go about concatenating and minifying those jQuery dependencies? I'm trying to get my site to load as fast as possible, and the less JS files it has to load the better. Also if it were possible to make them load asynchronously (using the async property for <script> tags) that'd be ace.

I'd rather do it without using a plugin but I will use a plugin if necessary.

Thanks for any help :)

5
  • 3
    Third party javascript files should be registered/enqueued by plugins as they are; not concatenated, modified or with another name. This way, if there are more than one plugin/theme that use the same third party js, Wordpress won't load several instance of the same code. To take advantage of this managament and concatenation, concatenation should be done on the fly combined with a cache system to avoid concatenate the files for each visit. I think this work is too much for an answer here. Take a look to W3 Total Cache; this plugin concatenate, minify, cache the result and load async js files.
    – cybmeta
    Aug 31, 2014 at 10:13
  • Just like @cybmeta says, W3 Total Cache do the job, but be careful with concatenate js files. Some scripts are not prepared to be "together" in in the same files. But relax too, the W3 Total Cache changes are all reversible. Sep 5, 2014 at 0:40
  • hey, thanks for answering, W3 Total Cache is working pretty well for concatenating etc, thanks for the suggestion (and @cybmeta) :)
    – Tom Oakley
    Sep 11, 2014 at 12:42
  • hey, thanks for answering and sorry I forgot to respond. W3 Total Cache works fine right now for this, and your explanation for why WordPress doesn't do it makes total sense. Thanks!
    – Tom Oakley
    Sep 11, 2014 at 12:42
  • 1
    This plugin is also nice if for some reason you don't want or need W3 Total cache wordpress.org/plugins/autoptimize
    – NickFMC
    Jan 13, 2015 at 20:32

1 Answer 1

1

W3 Total Cache offers JS/CSS minification. I'm not familiar with the process they use, but if you are wanting to avoid using a plugin, you could take a look at their source code how they handle it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.