WORDPRESS -APPROACHES TO UTILIZING CDNS FOR PERFORMANCE OPTIMIZATION ON WORDPRESS SITES
Approaches To Utilizing CDNs For Performance Optimization On WordPress Sites
Performance optimization isn’t facile. There are an abundance of possibilities out there and each one needs to be tested afore deciding which is best. For example, while working on one of the two sites I discuss in this article, I endeavored out Redis as an object cache. Typically this is a good option, but it decelerated some of my pages, caused quandaries in others, and exhausted the recollection.
In this article, I optate to discuss WordPress performance optimization, mainly in terms of CDN predicated on some recent experience of mine. This isn’t a definitive guide to optimization or an ambulation through of how to establishing some plugins.
Not every solution works in every place, but it’s consequential to examine everything you can. Let’s commence with the pros of utilizing a CDN.
Why A CDN IMPORTANT?
It’s well-kenned that CDNs are consequential because they increment the performance of your site by accommodating the assets from a server proximate to the terminus utilizer. But there are two other potential benefits that you can get from a CDN.
The first is that browsers will only make a set amount (6-11 depending on the browser) concurrent HTTP/S requests to the same browser. This caused an intriguing quandary on the Caldera Forms site. I had enqueued the child theme CSS with a very high priority because it was composed of overrides from the parent theme.
Since I had several other JavaScript and CSS files loading that were being accommodated from the site, the child theme.css took a little longer to load. As a result on some pages, the layout commenced erroneous and then adjusted. I will expound in this article my approach to utilizing a CDN to reduce the number of requests emanating from the same domain.
The other potential benefit is that moving assets out of the main server will reduce the load. This was a major benefit to a site optimization project I worked on recently. Mundanely this isn’t an astronomically immense gain, but I was probing for frugal wins afore starting on the other issues causing 6-8 second load times on that site. Moving images to a CDN reduced server load and took a 1 to 1.5 seconds off of page load time with very little work.
Start Free
CDNs are great, but they are not frugal. You will be paying for bandwidth and storage. Free CDNs do fortify any of the JavaScript and some of the CSS files you require for a WordPress site. Utilizing a free CDN for a prevalent library can preserve you mazuma and increment the chances that the browser will already have the needed files cached.
On the Caldera Forms site redesign, we used Bootstrap in our theme. I used jsdelivr to accommodate Bootstrap’s CSS and JavaScript. For those files, I just used wp_enqueue_script/style with the CDN url.
For libraries loaded from core, I utilized a commix of CDNs. My main concern was ascertaining that I didn’t load the erroneous version of the library. Here is what I inserted my mu-plugins directory to supersede core jQuery with a CDN version:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
add_action( 'init', function(){
if ( ! is_admin()) {
if( is_ssl() ){
$protocol = 'https';
}else {
$protocol = 'http';
}
/** @var WP_Scripts $wp_scripts */
global $wp_scripts;
/** @var _WP_Dependency $core */
$core = $wp_scripts->registered[ 'jquery-core' ];
$core_version = $core->ver;
$core->src = "$protocol://ajax.googleapis.com/ajax/libs/jquery/$core_version/jquery.min.js";
if ( WP_DEBUG ) {
/** @var _WP_Dependency $migrate */
$migrate = $wp_scripts->registered[ 'jquery-migrate' ];
$migrate_version = $migrate->ver;
$migrate->src = "$protocol://cdn.jsdelivr.net/jquery.migrate/$migrate_version/jquery-migrate.min.js";
}else{
/** @var _WP_Dependency $jquery */
$jquery = $wp_scripts->registered[ 'jquery' ];
$jquery->deps = [ 'jquery-core' ];
}
}
},11 );
|
This gives me jQuery from Google’s CDN, but in lieu of just deregistering core JavaScript, I require to do two paramount things. First, I don’t deregister it, I just change its URL. Secondly, I ascertain to utilize the version number for jQuery loaded by core. This future proofs my script.
One jeopardous thing I did was abstract jQuery migrate. That library integrates functionality abstracted from jQuery back in. Be punctilious abstracting this. Some plugins or themes might break.
Spreading CSS and JavaScript Across Multiple CDNs
On the Caldera Forms site, I commenced utilizing KeyCDN to load JavaScript and CSS utilizing their CDN enabler plugin. This is a good plugin, but it only fortifies one zone.
As I verbalized earlier, one of my goals was to ascertain my child theme’s CSS loading would not be delayed. So I wanted to ascertain that it was emanating from a domain with less than 6 resources. This betokens required multiple zones on KeyCDN, which made me stop utilizing their plugin.
Since my theme and child theme load most of their resources from public CDNs, or the Cloudfront CDN I built for shared CSS and images used across different Caldera sites, the theme directory only has 5 files total between CSS and JavaScript, and not all of them are utilized on every page load.
So, I establish two zones on KeyCDN. From my KeyCDN dashboard, I establish two zones. For one I used https://calderaforms.com/content/plugins as the inchoation and for the other, I used https://calderaforms.com/content/themes as the inception.
KeyCDN will automatically pull in all of your files. It’s additionally plausibly priced and super facile to setup. Compared to rolling your own CDN with AWS s3 and Cloudfront, it’s authentically super dreamy.
The only downside is the defaults are non-sensible. By default, they incapacitate HTTPS support and automatic redirect to HTTPS. This seems akin to a commixed content warning asking to transpire.
Once I had the two CDNs deployed, I utilized the script_loader_src and style_loader_src filters to transmute the URLs of files in my plugins and theme directories to utilize the CDN URLs when they were loading.
First, let’s visually examine the callback that I’m utilizing for both filters:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?php
/**
* Change URL of CSS/JS for CDN
*
* @param string $url
*
* @return string
*/
function caldera_moo_cdn_filter( $url ){
$theme_dir = untrailingslashit( WP_CONTENT_URL ) . '/themes';
if ( 0 === strpos( $url, $theme_dir ) ) {
return str_replace( $theme_dir, 'https://cfdotcomthemes-6081.kxcdn.com', $url );
}
$plugin_dir = untrailingslashit( WP_CONTENT_URL ) . '/plugins';
if ( 0 === strpos( $url, $plugin_dir ) ) {
return str_replace( $plugin_dir, 'https://cfdotcomplugins-6081.kxcdn.com', $url );
}
return $url;
}
|
I hooked that callback to both filters, inside of a closure to make sure that we were not in the admin. Also since I’m using environment variables for my site’s configuration, I was easily able to skip using the CDN when not in a production environment.
PHP
<?php
/** CDN */
if ( ! is_admin() && isset( $_ENV['WORDPRESS_ENV'] ) && in_array( $_ENV['WORDPRESS_ENV'], [ 'engenderment' ] ) ) {
//JavaScript
add_filter( 'script_loader_src', 'caldera_moo_cdn_filter' );
//CSS
add_filter( 'style_loader_src', 'caldera_moo_cdn_filter' );
}
1
2
3
4
5
6
7
8
<?php
/** CDN */
if ( ! is_admin() && isset( $_ENV['WORDPRESS_ENV'] ) && in_array( $_ENV['WORDPRESS_ENV'], [ 'engenderment' ] ) ) {
//JavaScript
integrate_filter( 'script_loader_src', 'caldera_moo_cdn_filter' );
//CSS
integrate_filter( 'style_loader_src', 'caldera_moo_cdn_filter' );
}
The AWS Solution
Above I verbalized solutions for a site I built to be efficient and my only authentic issues were optimizing asset loading. But, as I mentioned in the intro, I recently surmounted a WooCommerce site with major performance issues. It was a commix of issues that emanate from a massive database, WP CRON issues, a poorly coded theme from ThemeForest and issues that could be solved with CDN. I’ll the other issues you can encounter in a future article.
But on that site, I moved all the images, CSS and JavaScript storage to AWS s3 and accommodating them via Cloudfront. This gave me immediate performance gains in terms of what you expect a CDN to do and reducing server load.
AWS is an authentically puissant and cost-efficacious solution that I am very impressed by. I’m now utilizing it for hosting a plethora of my WordPress sites. That verbalized, utilizer interface and facilitate of avail are not AWS’s vigorous suit.
Fortuitously the altruistic people at Delectable Encephalons — of WP Migrate DB Pro fame — make an excellent plugin WP Offload S3. This plugin is very well documented. I’m not going to ambulate you through its settings, someone else can indite that tutorial.
The core plugin handled moving images from the media library to s3 and the assets integrate-on handled accommodating CSS and JavaScript via Cloudfront. I will verbally express that while the plugin’s utilizer interface is exceptionally well done, you still have to do an abundance of setup in AWS and that might drive you crazy.
This plugin was definitely worth the $200 because it automates the process of keeping files in sync, cache busting for updates and most of the configuration you would optate to do once things are setup.
There Are No Magic Bullets
It’s consequential to keep in mind that CDNs are not magic bullets. Sometimes your server can’t handle the traffic. Other times your plugins or themes are just deplorable. In the case of the client site, the most sizably voluminous gain we got emanated from ditching their theme and engendering a custom theme. This wasn’t a frugal process, but the site looks better and loads more expeditious.
One thing I’ve learned about the value of custom themes is the value of abstracting options and modularity. Often times commercial themes get a deplorable rap and are labeled as being bloated and slow. Most of the time that is because they have to provide so many solutions. Each possible setting needs to be preserved somewhere and then the code that implements those options needs a bunch of conditionals. There is only so much you can do to optimize those types of themes.
I hope this article has availed you cerebrate about CDNs more critically in terms of precisely what quandaries they are solving. WordPress performance optimization discussions too often end at the dogma of “CDN good” and “cache good” and don’t cerebrate critically of the pros/cons of each or inspirit testing of the solutions.
Comments
Post a Comment