Dynamic CSS

Caching Dynamic CSS in WordPress with URL Rewriting

Lately, I’ve been focusing a lot on improving website performance – getting sites to load as quickly as possible – sometimes in less than a second. W3 Total Cache handles just about every aspect of website performance. Page caching alone is a huge benefit to website load time on the first visit, and when you optimize browser caching for static resources, that makes navigating to other pages even faster. Add a CDN, and your static resources such as images, css files, and js files get downloaded at blazing speeds and take the load off your web server. Minification and file combining can help, but this can be tedious if you need to do it manually.

The Problem

One problem I have come across, though is some plugins and even themes that use dynamic css referenced as a separate file using a query string. A few culprits that use this method are the jQuery Accordion Menu Widget, the jQuery Mega Menu Widget, and even the latest version of PageLines.

Dynamic CSS?

Dynamic CSS does have some advantages – for one, it allows for a more user-friendly interface to configure various styling options without having to include lots of different css files for each option and as a result, can be a lot easier to maintain. The problem is that since the stylesheet doesn’t actually exist (it’s just the output of a php file based on a template css file), it never gets cached, so every time someone visits your site, it has to be generated and downloaded again. This means your visitors are going to be waiting longer for your pages to load. Not to mention, if you’re using a CDN, it won’t get processed properly.

So, how do we fix this?

One option is to just view the source and copy the stylesheet path including the variables into your address bar, copy the generated css, paste it into your theme’s stylesheet (or a separate one, if you like), and either set the widget to not use a skin (you’ll also have to copy the image resources into the proper location on your theme) or comment out the section where the dynamic php is referenced in the plugin/theme. I haven’t looked at how this is handled in Pagelines, but in the jQuery Mega Menu plugin, the stylesheet is simply echoed, so you can’t just dequeue and re-enqueue outside of the plugin, unfortunately.

URL Rewriting

We can handle this with a bit of URL rewriting. The first step is to get Apache to point our fancy url to the actual URL. The method used is one I found in an article  on Terminally Incherent. Of course, I had to modify it a tad to get it to work for my purposes, but this is was the end result:


<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on
RewriteBase /wp-content/plugins/jquery-mega-menu

RewriteRule ^([^/]+)-([^/]+)\.css$ skin.php?widget_id=$1&skin=$2 [NC]
</ifmodule>

This will actually work for both jQuery Accordion Menu Widget and jQuery Mega Menu Widget, as they both use the same filename and query string (of course, you’ll need to change the rewrite base accordingly). This file goes inside the specific plugin folder, not the root or your site.

This will let us reference the dynamic stylesheet with a url that looks like an actual file. For example, if I’m using widget_id 2 with the “white” skin, the original url would have been:

http://somesite.com/wp-content/plugins/jquery-mega-menu/skin.php?widget_id=2&skin=white

but now, we can use:

http://somesite.com/wp-content/plugins/jquery-mega-menu/2-white.css

The second half is actually making the plugin reference the stylesheet using the fancy url, and we’ll need to modify the plugin to make this happen.

This file doesn’t actually exist, but since it looks like a file and doesn’t have any query strings, it can be cached, and it can also be mirrored by your CDN.


change

."/skin.php?widget_id=".$key."&amp;skin=".strtolower($skin)."\"

to

."/".$key."-".strtolower($skin).".css\"

And that’s it! your css will now be cached and/or mirrored by your CDN, which should cut at least 200ms off your load time.

The Proof

Before:

 

 

 

 

After:

 

 

 

 

Reverting WordPress Plugin Updates

Sometimes, while an update for a particular plugin might be rock solid, it might hinder the functionality of another plugin, so you end up having to roll that plugin back till you can fix the problem.

That means you have to either download the previous version of that plugin, extract it, and then upload it via ftp, which could take a really long time.

You could also upload the zip, and then use the web-based file manager to extract the file to overwrite the plugin update if your web host has that functionality, which would save some time, but it’s a bit more work.

What if, prior to any update, a snapshot of your db was taken (optional) and a copy of the current version of whatever you were updating was backed up on the server – all automatically. That way if the update created a problem, you could just “rollback” or “un-update”, and the update would be quickly reversed.

Maybe this is just me wanting to be lazy, but I think this would be a huge benefit to a lot of people, and I haven’t been able to find anything that does that. I’m pretty sure all the individual steps are doable, and I’ve seen several posts for at least the last 3 years, and the answer is always “no, you have to do it manually”

Now, it may not be feasible to automate restoring from a database backup, but in most cases, you only need to replace the plugin files to restore the functionality of the previous version.

There may be a solution for this that I haven’t come across, and there may be a reason this shouldn’t be done, but I think I’m going to try creating this solution. Any feedback is welcome.

 

Speed-up-your-ranking

How to Speed up WordPress

After you’ve improved to you site’s keyword density, set up all the proper meta tags, configured your robots.txt, and generated and submitted your sitemap.xml, to ensure you site rank is as high as possible, you’ll want to optimize your site speed. The general recommendation is to keep your site’s load time under 2 seconds.

Aside from the obvious effect of a slow site to visitors, Google has been factoring site load time into the Page Rank formula since April 2010. There are many factors that can contribute to load time, and the steps you’ll need to take will be dependent on those factors.

There are a number of different methods you can take to analyze your site’s load time. The best place to start is a site speed test site such as Pingdom or WebPageTest. WebPageTest is a bit more detailed and comprehensive, and Pingdom is a bit simpler to understand. Also WebPageTest takes about 5 times longer to run. Both will display a waterfall style horizontal graph displaying the load time of each item.

Pingdom graph colors

Most of your load time will most likely fall under connect and/or receive. We’ll get to what to do about those a bit later. After you’ve reviewed the graph, check out the Performance Grade for Pingdom or Performance Review for WebPageTest. These will give you actionable recommendations for ways to reduce your load time. Most of the recommendations will likely involve caching, so lets start there.

Caching Types

There are a number of types of caching, and while the W3 Total Cache WordPress plugin handles all of them, it can be complicated to configure, and some options may not work depending on your hosting plan, so I’d like to review the types of caching.

 

Page Caching

Dynamic Content Management Systems such as WordPress can be immensely versatile and easy to manage, but they can tend to put a greater load on a web server than necessary. For static pages, and even for most posts, it makes more sense to write the content for each page/post to static files and serve them up when each page is visited rather than to process all the php and sql queries each time. Each file is refreshed whenever the page/post is updated, so the static files won’t contain outdated content.

While, as previously mentioned, the W3 Total Cache plugin will handle page caching, it may not perform page caching well in all hosting environments. In these circumstances, I find that Quick Cache also works well for page caching and doesn’t conflict with W3 Total Cache (as long as you have page caching disabled).

Minify

While not technically caching, it can certainly be a dramatic benefit in conjunction with caching. Minification is simply removing unnecessary white space from text files like HTML (or HTML rendered from PHP) Javascript and CSS. While it’s usually safe to minify HTML and inline JS and CSS, dynamically minifying external JS and CSS can result in a failure for those files to load properly, so it’s usually best to manually minify those files using a tool such as YUI Compressor.

Browser Caching

This greatly helps to offset the load time of static files as well as the overall load time of the site when revisiting the same page, or visiting additional pages on the same site. In addition to the obvious benefits of  configuring headers to promote browser caching, if a Proxy Caching Server exists on a user’s network, its possible that the site load time will be lessened even on the user’s first visit to the site. If you update your CSS or JS files frequently, it’s important to append a query string to these static resources to ensure that the latest version of these files are loaded.

 Further Analysis

There may be times when all the above methods still fail to bring your site’s load time down to a reasonable time. Enter the P3 (Plugin Performance Profiler) Plugin. This plugin will analyze the impact that each plugin has on your site’s load time as well as the impact of your theme. It’s possible that a single plugin may be the culprit.

Moving Javascript to Footer

When Javascript loads in the header, it unnecessarily increases the load time. It’s a fairly simple task to force javascript to load in the footer. If you’re enqueue-ing you’re own scripts, you can simply change this:

wp_enqueue_script(
		'custom-script',
		get_template_directory_uri() . '/js/custom_script.js',
		array('jquery')
	);
to this
wp_enqueue_script(
		'custom-script',
		get_template_directory_uri() . '/js/custom_script.js',
		array('jquery'), false, true
	);
If you're using several plugins that load javascript, you can use the Javascript to Footer plugin.

Image Optimization

Ensuring your image file sizes are as low as possible can improve your site’s load time by up to 10% without degrading image quality. There are many tools available for lossless image optimization, but probably the most reliable and comprehensive is Yahoo’s Smush.it. Yes, there is a plugin for that WP Smush.it will run images through Smush.it as you upload them to your site, or you can select to process several in bulk from your media library. This can be incredibly slow, and if you have dozens of images to process at once, your server may timeout if attempting to process too many at once. If you’d rather optimize dozens of them before uploading them, there is a command line utility that uses the Smush.It web service.

wordpress-logo

What is WordPress?

For anyone not familiar with the  most popular website platform today, allow me to enlighten you. WordPress is a Content Management System or CMS. One advantage of a CMS is that it allows people who don’t know HTML to update the content of their website without having to worry about breaking anything. This can save a small business owner from having to pay a webmaster on a regular basis. You might need to spend a little money getting it set up initially, but in the long run, it can be much more cost effective than the alternatives.

To be clear. WordPress is free, installation is easy – you don’t need to be technically inclined to install it. With some web hosts, such as Hostgator, it’s  a two-click installation. There are hundreds of free themes and plugins available out there, though you may want to pay a little for a premium theme or for a developer to customize your theme so it’s a bit more unique.

Ubiquity

WordPress is ubiquitous. It runs almost 70 million sites wordwide – granted, about half of those are hosted by WordPress.com, but the other half are self-hosted. Not all of these are personal blogs, a significant percentage of the best sites on the web are powered by WordPress. Some of the businesses that use WordPress for their website are CNN, NFLNetwork SolutionsTechCrunch, and Ripley’s (Believe it or not!). For a longer list of businesses running websites on WordPress, click here. The point is that not only is WordPress easy to use, it’s also very flexible.’

Modularity

This flexibility comes largely from its modular design. There are a base set of features that come with WordPress out of the box, such as a WYSIWYG editor, a handful of basic widgets, two different content types (you can add static pages as well as blog posts), user registration, an RSS feed, multiple authors, and multiple security levels. The styling and structure of your content is handled by WordPress Themes, and you can add functionality using WordPress Plugins. This is not a hard and fast distinction, as there are many Themes which also add functionality, and there are many Plugins which also affect styling, but generally speaking, Themes are primarily for the layout, and Plugins are generally for adding (or removing) functionality.

Support

Possibly the number one reason that WordPress is so ubiquitous is the community support. The Documentation is fairly thorough, but it can be a little daunting to navigate, so if you’ve perused the documentation and you still have questions (or if you’re just not sure where in the documentation to start), then post a question in the Forums. Most basic questions get answered in a matter of hours. It might take longer if you have difficulty getting across what you’re looking for, but most users are happy to help.

dropbox

New Dropbox API

In September, I posted about Pressbox, an awesome WordPress plugin that intuitively lets you link to documents and images in your Dropbox account. If you’ve downloaded this plugin or pretty much any other similar plugin in the past week or so, you may have noticed it doesn’t work. It’s not the plugin’s fault, though. Dropbox released a new API on October 21st. According to this post, the previous version “still works exactly as it did before”. This is true if you have an application that had already been authorized with a token – all WordPress Dropbox plugins require you to create your own “app” under your Dropbox account.

The new API adds some pretty significant new functionality, though. It’s more secure, and it allows you to have an app-specific folder instead of just giving it full access to your whole Dropbox, though you can still do that too. You can stream media straight from your dropbox account, which is pretty huge in and of itself. You can search for files in your dropbox account, create shareable links to files, and you can manage file revision history, which makes using Dropbox for collaboration a lot more effective.