Loading JavaScript In Footer In WordPress 2.8

As you may all know by now, WordPress 2.8 will have some optimization done on JavaScript as well as CSS. That includes concatenating the scripts/styles, minifying it instead of packing as well as gzipping. I have been paying much attention to the development of WordPress 2.8 especially when it comes to JavaScripts. I have filed 2 suggestion tickets in WordPress Trac, Ticket #8884 and Ticket #8859 which should be able to help plugin authors load their JavaScript easily in the footer of WordPress.

This post shall be a tutorial post and I will demonstrate how to load JavaScript in the theme’s footer in WordPress 2.8 Nightly using my WP-Polls as an example.

### Function: Enqueue Polls JavaScripts/CSS
add_action('wp_enqueue_scripts', 'poll_scripts');
function poll_scripts() {
	wp_enqueue_style('wp-polls', plugins_url('wp-polls/polls-css.css'), false, '2.50', 'all');
	wp_enqueue_script('wp-polls', plugins_url('wp-polls/polls-js.js'), array('jquery'), '2.50', true);
	wp_localize_script('wp-polls', 'pollsL10n', array(
		'ajax_url' => plugins_url('wp-polls/wp-polls.php'),
		'text_wait' => __('Your last request is still being processed. Please wait a while ...', 'wp-polls'),
	));
}

The poll_scripts() function will hook onto the wp_enqueue_scripts function. This will allow you to enqueue JavaScripts as well as CSS Styles for your plugin.

As the name goes, wp_enqueue_style() will queue and then print out your plugin’s CSS link.

wp_enqueue_script() will queue and then print out the JavaScript link. The difference between WP2.7’s wp_enqueue_script() and WP2.8’s wp_enqueue_script() is the addition of the last argument which is whether to load the JavaScript in the footer. If set to true, it will load it in the footer, PROVIDED that your theme has the following code:

in the theme footer (refer to the default theme footer.php if unsure). Many themes especially self-created ones has failed to include wp_head() in the header.php as well as wp_footer() in the footer.php. The default value of the last argument is false, which means it will load it in the header by default.

wp_localize_script() will allow your to translate strings within your plugin JavaScript. To access the translated variable, you can use “pollsL10n.text_wait” (without the quotes).

This new hook:

do_action('admin_enqueue_scripts', $hook_suffix);

will allow you to enqueue your plugin JavaScript or CSS within the WP-Admin area easily rather than calling many times add_action() repeatedly depending on how many pages your plugin has in the WP-Admin area.

The sample code from WP-Polls to print JavaScripts as well as CSS in the WP-Admin area are as follows:

### Function: Enqueue Polls Stylesheets/JavaScripts In WP-Admin
add_action('admin_enqueue_scripts', 'poll_scripts_admin');
function poll_scripts_admin($hook_suffix) {
	$poll_admin_pages = array('wp-polls/polls-manager.php', 'wp-polls/polls-add.php', 'wp-polls/polls-options.php', 'wp-polls/polls-templates.php', 'wp-polls/polls-uninstall.php');
	if(in_array($hook_suffix, $poll_admin_pages)) {
		wp_enqueue_style('wp-polls-admin', plugins_url('wp-polls/polls-admin-css.css'), false, '2.50', 'all');
		wp_enqueue_script('wp-polls-admin', plugins_url('wp-polls/polls-admin-js.js'), array('jquery'), '2.50', true);
		wp_localize_script('wp-polls-admin', 'pollsAdminL10n', array(
			'admin_ajax_url' => plugins_url('wp-polls/polls-admin-ajax.php'),
			'text_delete_all_logs' => __('Delete All Logs', 'wp-polls'),
		));
	}
}

Firstly, I assigned all the pages of WP-Polls that has an admin page to an array. Next I check whether the current page is within the array. If it is in the array, it means that the user is accessing WP-Polls admin area and thus, I will proceed on to enqueue the JavaScript or CSS needed in the WP-Polls admin area.

Note 1: When you use wp_enqueue_script(), it will automatically register the script and then print it out, whereas if you use wp_register_script(), you will have to manually print it out by calling wp_print_scripts().

1 Star2 Stars3 Stars4 Stars5 Stars (127 votes, average: 4.06 out of 5)

60 thoughts on “Loading JavaScript In Footer In WordPress 2.8”

  1. I hope this or something like this will be written in wordpress codex. Thanks, for now I bookmark this page. It definitely comes in handy.

  2. Any particular reason you’re doing the wp_enqueue_script()’s inside a hooked function rather than just when the plugin is loaded? I’ve never done it that way before and wondering the reasoning behind it.

  3. Hi Viper007Bond,

    I thought “wp_enqueue_scripts” hook is for plugins to enqueue all the JavaScripts/CSSs to the hook and I think that is the reason why I did it there. Previously I did it in the hook wp_head which I did register_script and then print_script. I figure out it is better to just call 1 function to register and print at the same time and hence I decided to go for the enqueue script in the wp_enqueue_scripts hook.

  4. All my non-tiny plugins run inside a class. I start up the class at the “plugins_loaded” hook and register all my hooks here (add_action and such). When I’m doing that, I also do the wp_enqueue_script()’s. Seems to work fine and had never thought of doing it any other way.

    Hmm.

  5. Oh I see, I think there are quiet a number of ways to do it. For me, I am not really a OO person. I think it is the same because the internal wp_print_scripts() will be called in the wp_head. and hence if you enqueue any script before wp_head(), the effect will be the same

  6. Any hook that runs before wp_head() or admin_print_styles can be used to queue scripts but wp_enqueue_scripts is more convenient as it gives access to is_page(), is_single(), etc. Also admin_enqueue_scripts is more convenient as it gets the current admin page hook as argument so plugins can add scripts only where needed.

  7. One of the most debilitating problems with wordpress is the way plugins are allowed to populate pages globally with javascripts and style sheet requests. Typically a plugin only uses one page where it needs these scripts but still dumps unwanted overheads on the rest of the site pages. This is avoidable through proper programming, but many programmers either don’t know how, or don’t bother to do this. One of the most crucial improvements to wordpress performance is getting rid of this dead weight. A further downside is the possbility of calling duplicate scripts like jquery that increasing http requests. Putting javascripts in the footer is a good move, but better still let’s find a sure fire way to remove unwanted weight altogether untill it is needed, or at least empower the webmaster to control what and when scripts are loaded into the header.

  8. It is possible to load only JS at certain pages in WP-Admin but not on the front end. Taking an instance of my plugin WP-Polls, I will not know when the user will have a poll within the page, and to play safe just load it at global. But since loading has been moved to the footer, it is easier to set a variable and check the variable at the end of the page.

    I am still waiting for the API to compess and combine JS scripts on the front end as well as currently it is being done at the backend and it only allows WP JS and do not really have an API.

  9. I would suggest that the write/ edit page of wordpress has an extra meta box that listed via drop down all the installed plugins. The function would work with these set of rules.
    1- all plugins are allowed to load globally if nothing selected.
    2- if a plugin or multiples are selected ONLy their scripts are loaded on that page.

    This would allow the webmaster to determine exactly what is loaded on every page at the point of publication.

    Maybe sets of scripts should be availbale, so set say wordpress default scripts can be created and selected from the write page and different sets for different needs. This meta box could be hiddeen to non admins of the site. Seems like a small extra for a lot of performance benefit!

  10. Hey,
    Thanks for the post.
    But, the WordPress 2.8 is still is beta 2 stage. So, I guess this glintch will be rectified in the final release.

  11. As I did in some plugins, in the options panel can be added a simple control that loads the footer.php of a theme (if present) ad a string and check the “wp_footer()” substring”.

    That helps non technical users to know their theme has,potentially, a problem.

Comments are closed.