Resource Replace, update js and css domain links

Back

Changing domain names of javascript and css files in WordPress

Today I was looking through WordPress plugins trying to find a plugin that updated domain names for resources like images, javascript, and css to point somewhere else. Mainly, I wanted some javascript and css to be served from a CDN, and didn't want/need the bloat of something like w3tc. While it's one of the best known plugins and handles a lot of functionality, the bugs in it are sometimes disastrously crippling to a site.

So, as it often is, I decided to write my own plugin to handle what I wanted. In order to filter out css and javascript source links, I ended up hooking into the style_loader_src and script_loader_src hooks.

To be honest, you don't need a plugin for this type of functionality, openning up your functions.php file in your theme and adding the following would do the same thing:

add_filter( 'style_loader_src', 'css_js_domain_replace_function');
add_filter( 'script_loader_src', 'css_js_domain_replace_function');
function css_js_domain_replace_function($src){
    if( is_admin()  ) return $src;

    $src = str_replace(site_url(), 'maybe-some.cloudfronturl.here', $src);
    return $src;
}

Though my plugin allows for you to split the domain names for js or css as well as specify ignore patterns so that if you have some css that's generated by your server or something, you can make sure you dont replace that particular file's domain.

The plugin is called Resource Replace and is available on github for anyone to use. Granted that they include the MIT License with it and all that other goodness.

A note though, if you do not include your javascript and css in the proper "wordpress way", then this plugin is not going to help you. You need to update your theme to use wp_euque_* functions if that's the case. If you're looking for a solution around that, you can surrounded your wp_head or get_header function in output buffering and to a replace on the captured string.

Other Posts

comments powered by Disqus