Question

WP has a nice javascript loader included in wp-admin: http://core.trac.wordpress.org/browser/tags/3.0.4/wp-admin/load-scripts.php

and a CSS loader: http://core.trac.wordpress.org/browser/tags/3.0.4/wp-admin/load-styles.php

I was wondering if it's possible to use them in the front-end too, not just admin, because they can concatenate all enqueued scripts, and serve them as a single gzipped file

Was it helpful?

Solution

late answer

From a brief look:

You'd have to use

  • include( admin_url().'load-scripts.php' );
  • and include( admin_url().'script-loader.php' );

Then jump into $GLOBALS['wp_scripts']:

Use…

$wp_scripts->default_dirs( array_merge( 
     $wp_scripts->default_dirs
    ,array( '/themes/your_theme/js/' ) 
); 

…to extend it.

And then use

$wp_scripts->add( $handle, $path_from_content_dir, false/array( $deps ), $ver ) 

to add a script.

Notes:

  1. Uncompressed scripts get searched by .dev.js (when SCRIPT_DEBUG is TRUE).
  2. Same seems to be possible for $wp_styles.
  3. EDIT: WP 3.5 will change this behavior and use .js for "dev" versions and ".min.js" when (SCRIPT_DEBUG is TRUE);

(But I guess this will only work if you use a plugin or mu-plugin.)

It´s not tested and I´m not shure if this will work.

OTHER TIPS

This is a very good question and would be a great feature for WordPress to include.

Some of the other answers don't address the main question.

I was wondering if it's possible to use them in the front-end too, not just admin, because they can concatenate all enqueued scripts, and serve them as a single gzipped file.

No it's not currently possible to use the built in script loader to Concatenate css and scripts for the front end.

There was a discussion about this on WP Hackers a few years ago and there is a trac ticket for this enhancement that has been accepted but for a future release.

If you need to enqueue a CSS file on the front end:

1) Register the style via wp_register_style( $handle, $src ) 2) Hook wp_enqueue_style( $handle ) into the wp_print_styles hook.

If you need to enqueue a script on the front end:

1) Register the style via wp_register_script( $handle, $src ) 2) Hook wp_enqueue_script( $handle ) into the wp_head hook.

(Note: I would have expected the wp_print_styles hook for this, but this hook apparently does not work as expected.)

I have a few scripts you may wish to look at.

1. Combine.php - On a number of my themes I have implemented this script. It supports similar functionality and can be dropped into your template folder and worked with relatively easily.

2. WP Minify - This plugin supports minifying and is very easily to work with.

3. W3 Total Cache - is a very powerful performance plugin. It also supports script/css combination as well as a large number of other features e.g. off loading the combined scripts to a CDN.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top