Asset Helper

Current version: 1.1 (changelog)

Includes functions for CSS, JavaScript, and images:

  • stylesheet_tag()
  • javascript_tag()
  • image_tag()

At their most basic, these functions create the appropriate HTML tags for the supplied arguments. The benefit comes from the additional features of these functions: timestamping and asset hosts.

This library was inspired by the Ruby on Rails AssetTagHelper. It covers the basic functionality of the Rails helper for now; further improvements may be made in the future. This code works both as a library you can include in your own applications, or a Wordpress plugin for use in your themes.

Download Asset Helper from the Wordpress plugin directory

Note: The code in the Wordpress plugin directory is used for both Wordpress and non-Wordpress sites. Download it there even if you aren't using WP.

Timestamps

All functions will append ?1234567890 to file URLs, where this string is the Unix timestamp of the file's last modified time. This value will automatically change when the file is changed, and enables long-term caching when it does not change.

To best take advantage of this, configure your web server with far-future expiration times for your static files. In Apache, that means putting something like this in your .htaccess file or VirtualHost container:

ExpiresActive On
<FilesMatch "\.(ico|gif|jpe?g|png|js|css)$">
	ExpiresDefault "access plus 1 year"
</FilesMatch>

For more information, see the Yahoo Developer Network performance tips and Apache's mod_expires documentation.

Asset Hosts

Using a separate hostname for static files can improve your page loading speed by allowing browsers to download more files in parallel. You can benefit from this even if you're not using multiple web servers.

The easiest way to take advantage of this functionality is to first create a DNS record for your desired static asset host, such as static.example.com and then configure your web server with this hostname pointed to the same directory as your web site.

More advanced usage would involve a front-end static file server like Nginx that proxies dynamic requests to an Apache/mod_php backend (or similar setup). Describing how to do this is beyond the scope of this documentation but the asset host functionality will work identically in this type of configuration. Note that for timestamping to work, this plugin needs filesystem access to the files in question, so the timestamping functionality only works if the files are physically on the same server.

Finally, add the following line to your application's configuration file or anywhere that will make it available to every page (if you're using the Wordpress plugin, put it in wp-config.php):

define('ASSET_HOST', 'static.example.com');

With this constant set, the Asset Helper functions will all return full URLs using this alternate hostname. These functions are also smart enough to figure out if SSL should be used, so don't worry about setting a protocol.

For more information on the benefits of static file servers, see the Yahoo Developer Network performance tips.

Installation

Installing Asset Helper is easy. Just unzip the package, include asset-helper.php in your application, and start using it.

<?php include_once 'asset-helper.php'; ?>

If you're using it as a Wordpress plugin, unzip it into your plugins folder, activate it via the WP plugins panel, and you're set. Alternately, you can skip the activation step and follow the instructions above, including it from your functions.php or header template. For WP sites, however, installing it as a plugin allows you to take advantage of the automatic plugin update notifications, so this is the recommended method.

Function Reference

In order to "just work", Asset Helper makes a few assumptions about where your files live. By default, stylesheets, JavaScript, and images are all assumed to be located in /css, /js, and /images, respectively. To override this, either specify a full path to the files you're using or initialize an array called $asset_helper_subdir somewhere in your code before Asset Helper is loaded.

For example, if you prefer keep your CSS files in /stylesheets, simply place this line above the inclusion of Asset Helper:

$asset_helper_subdir['css'] = '/stylesheets';
include_once 'asset-helper.php';

For Wordpress sites, it's assumed that CSS and JS files will live in your theme directory, while images are in a subdirectory called images inside your theme directory. Setting $asset_helper_subdir on WP sites has no effect. For illustration purposes, the Wordpress examples below all show a default Wordpress installation in your site's root directory. In real use the URL path will reflect the actual path to your current theme location.

stylesheet_tag()

<?php stylesheet_tag($files); ?>

This function can be used with one or more arguments. Arguments can be provided as a list of strings; each one will result in a separate <link /> tag. You can provide simply a filename, a filename without an extension, a full URL path, or a complete URL. Paths that do not begin with a slash will be created relative to the default CSS location.

Wordpress users can omit the argument entirely: if no argument is provided, it will print a <link /> tag to the standard Wordpress style.css for your theme. This has no effect when used on a non-wordpress site; the function will not print anything at all.

Example usage

The first example shows the output for both a Wordpress and non-Wordpress site. I've omitted the WP examples for the rest but all methods of calling this function work identically.

<?php stylesheet_tag('extras.css'); ?>
// => <link rel='stylesheet' href='/css/extras.css' type='text/css' />
// => <link rel='stylesheet' href='/wp-content/themes/theme-name/extras.css' type='text/css' />
 
<?php stylesheet_tag('extras'); ?>
// => <link rel='stylesheet' href='/css/extras.css' type='text/css' />
 
<?php stylesheet_tag('new/styles.css'); ?>
// => <link rel='stylesheet' href='/css/new/styles.css' type='text/css' />
 
<?php stylesheet_tag('/stylesheets/foo.css'); ?>
// => <link rel='stylesheet' href='/stylesheets/foo.css' type='text/css' />
 
<?php stylesheet_tag('http://www2.example.com/css/foo.css'); ?>
// => <link rel='stylesheet' href='http://www2.example.com/css/foo.css' type='text/css' />
 
<?php stylesheet_tag('main.css', 'extras.css', 'ie6-bugfixes.css'); ?>
// => <link rel='stylesheet' href='/css/main.css' type='text/css' />
// => <link rel='stylesheet' href='/css/extras.css' type='text/css' />
// => <link rel='stylesheet' href='/css/ie6-bugfixes.css' type='text/css' />
 
/* Wordpress users only */
<?php stylesheet_tag(); ?>
// => <link rel='stylesheet' href='/wp-content/themes/theme-name/style.css' type='text/css' />
 

javascript_tag()

<?php javascript_tag($files); ?>

This function can be used with one or more arguments.

Arguments can be provided as a list of strings; each one will result in a separate <script></script> block. You can provide simply a filename, a filename without an extension, a full URL path, or a complete URL. Paths that do not begin with a slash will be created relative to the default JavaScript location.

Example usage

As above, I'm showing one example from Wordpress but, again, all methods of using this function will work correctly.

<?php javascript_tag('javascript.js'); ?>
// => <script src='/js/javascript.js' type='text/javascript'></script>
// => <script src='/wp-content/themes/theme-name/javascript.js' type='text/javascript'></script>
 
<?php javascript_tag('javascript'); ?>
// => <script src='/js/javascript.js' type='text/javascript'></script>
 
<?php javascript_tag('third-party/jquery.js'); ?>
// => <script src='/js/third-party/jquery.js' type='text/javascript'></script>
 
<?php javascript_tag('jquery.js', 'application.js'); ?>
// => <script src='/js/jquery.js' type='text/javascript'></script>
// => <script src='/js/application.js' type='text/javascript'></script>
 

image_tag()

<?php image_tag($file, $options); ?>

This function works a bit differently than the others. It only allows for one image per function call, but lets you set any HTML attributes you need for the image.

The first argument is the image itself, either a filename, URL path, or complete URL. Paths that do not begin with a slash will be created relative to the default image directory.

The second argument is an associative array of options corresponding to HTML attributes/values. One special option is 'size', which can accept image dimensions as a single string, saving you the trouble of adding both width and height attributes (which you're welcome to do if you prefer). All options are optional (ha!); if an alt attribute is not supplied, one will be created from the image filename to ensure HTML validity.

The 'size' attribute should be in the format WIDTHxHEIGHT. For example, use '300x100' to specify a width of 300 and a height of 100.

Example usage

Once again, one Wordpress example provided but all the rest work as well.

<?php image_tag('logo.png'); ?>
// => <img src='/images/logo.png' alt='logo.png' />
// => <img src='/wp-content/themes/theme-name/images/logo.png' alt='logo.png' />
 
<?php image_tag('subdir/logo.png', array('size' => '300x100', 'alt' => 'Alternate text')); ?>
// => <img src='/images/subdir/logo.png' width='300' height='100' alt='Alternate text' />
 
<?php image_tag('logos/logo.png', array('alt' => 'Alternate text')); ?>
// => <img src='/images/logos/logo.png' alt='Alternate text' />
 
<?php image_tag('/photos/photo.jpg', array('class' => 'css_class', 'id' => 'some_id')); ?>
// => <img src='/photos/photo.jpg' alt='photo.jpg' class='css_class' id='some_id' />
 
<?php image_tag('/images/logo.png', array('onmouseover' => 'do_something();')); ?>
// => <img src='/images/logo.png' alt='logo.png' onmouseover='do_something();' />
 

License

Asset Helper is released under the terms of the GNU General Public License (GPL) version 2. If you find this code helpful, a link back to my site would be cool, but it’s not required.