Page Load on Speckyboy Design Magazine https://speckyboy.com/topic/page-load/ Resources & Inspiration for Creatives Sun, 16 Feb 2025 21:10:10 +0000 en-US hourly 1 https://speckyboy.com/wp-content/uploads/2024/03/cropped-sdm-favicon-32x32.png Page Load on Speckyboy Design Magazine https://speckyboy.com/topic/page-load/ 32 32 6 Best WordPress Plugins to Optimize & Speed Up Your Website https://speckyboy.com/wordpress-speed/ https://speckyboy.com/wordpress-speed/#respond Tue, 12 Nov 2024 23:33:16 +0000 https://speckyboy.com/?p=95796 With these plugins, you will be able to quickly speed up and optimize your WordPress website to be in tip-top error-free shape.

The post 6 Best WordPress Plugins to Optimize & Speed Up Your Website appeared first on Speckyboy Design Magazine.

]]>
Websites running WordPress can slow down for any number of reasons. It could be anything from bloated code, a rogue plugin, or poor hosting performance. Figuring out what’s slowing you down is hard enough, and harder still is that some methods for increasing speed (caching plugins, for instance) are full of cryptic settings.

It can all add up to something of a nightmare in diagnosing and fixing what would seem to be a simple problem.

That’s where we’ve come in to help. There are tools out there to help simplify the process of satisfying your need for (WordPress) speed. Below, we’ve compiled a collection of plugins that don’t require a rocket science degree.

They will, however, help you build a blazing-fast site. Plus, we’ll offer tips for getting the most performance out of your WordPress website.

Surge for WordPress

If you’re stressed by the idea of a complicated settings panel, you’ll want to check out Surge. This caching plugin requires zero configuration, and it automatically builds a cache and clears files as you update your website.

Not only is this plugin super simple to use, but it’s also free. Optimizing your site’s performance is only a few clicks away.

Surge

WP Rocket

Setting up a WordPress cache plugin can be an incredibly frustrating experience. There are often so many settings with not-so-obvious names that you have to do a lot of testing to find out what something does.

WP Rocket is a premium plugin, but it may just be worth the cost. It features an ultra-minimal setup and really does speed up your site. The package includes page caching, preloading, database optimization, and lazy loading of images.

WP Rocket

Fast Velocity Minify

Fast Velocity Minify will combine your site’s CSS and JS files into smaller file groups. After all, each one of these files can be thousands of lines long.

Compressing and combining files can greatly cut down on load time, especially for sites running lots of plugins. The setup is relatively easy, with the default settings getting the job done. There are also advanced options available if you’re feeling adventurous.

Autoptimize

With just a few clicks, Autoptimize will concatenate styles and scripts, minify HTML, CSS, and JS files, add expiry headers, and cache them. The plugin can also move styles to your site’s header and scripts to your site’s footer.

While the developer recommends using Autoptimize in conjunction with a caching plugin, it’s still a simple way to speed up your site.

Speed Booster Pack

Speed Booster Pack utilizes several techniques to speed up your site. It minifies HTML/JavaScript/CSS but also does so much more. For example, it will compress images, load JavaScript libraries from Google’s servers (rather than from your own server), defer the parsing of scripts, remove ‘junk’ headers, and make other useful tweaks.

Inside the plugin settings, peak memory usage and page load times are displayed. Just check the boxes next to each option you want to enable. You also have the option of disabling specific scripts from being minified.

Speed Booster Pack

Optimize Database after Deleting Revisions

Your site’s database can become incredibly cluttered over time, leading to sluggish performance. Optimize Database after Deleting Revisions aims to be a “one-click” solution by deleting post revisions (you can keep a specified amount of revisions per post), spam comments, unused tags, pingbacks/trackbacks and orphan post meta items.

It also optimizes database tables to help keep your DB lean and clean. Optimizations can run hourly, once daily, twice daily, or weekly. It’s compatible with WordPress multisite.

Tips for Increasing WordPress Speed

WordPress, by itself, is a fast platform. But as we add components like themes and plugins, it can get weighed down. Combined with database clutter and potential hosting issues, a site can slow to a crawl.

Here are a few things to take into account when you’re looking to increase speed:

Avoid Heavy Themes

Just because a theme calls itself “minimal” doesn’t mean it’s lightweight. A theme may sport a minimalist look but still load a ton of scripts that will slow you down.

If you’re using a third-party theme, check the documentation to see how to disable scripts you don’t plan to use. Otherwise, use a lightweight starter theme and build for what you need.

Do You Really Need that Plugin?

Each plugin you install and activate can add scripts, styles, and database entries. Before you install a plugin, research to see if it’s known to cause any issues with load times. Ask yourself if it’s a necessity for the success and security of your site. If not, you may want to move on for the time being.

Make Note of Remote Scripts & Styles

Services that provide web fonts, analytics, or ad-serving capabilities can affect speed. While these providers may have fast remote servers, any sort of connection issue can grind page loading to a halt.

Be aware of what services you’re using and only use those that are necessary. For that matter, it’s also a good idea to stick with well-known and trusted providers.

Watch for Missing Content

Whether local or remote, look out for scripts or stylesheets that fail to load. A missing file can cause your site to react incredibly slowly, along with possible display and functionality consequences.

Use a tool like, PageSpeed Insights, Pingdom, or GTmetrix to analyze your site. Some tools offer a “waterfall” view that shows how long it takes for each file to load along with your page. If one of these files generates a 404 error, you’ve found the culprit.

Be Aware of Hosting Limitations

Not all web hosts are created equal. Some just flat-out provide a better product. But you should also be aware of hosting-related issues that can cause a slowdown. Being on an overcrowded server, running a non-supported (old) version of PHP, or having too much traffic on a shared hosting account can all cause problems.

Getting up to Speed

Bringing your WordPress site up to top performance doesn’t have to be difficult. Using the tools and techniques above, you’ll have everything you need to make improvements.

Speed is vitally important, after all. It affects things like SEO and your bounce rate. It’s worth the little effort to squeeze as much performance out of your website as possible.

WordPress Speed FAQs

  • What Are Optimization Plugins for WordPress?
    They’re plugins designed to improve the performance and efficiency of your WordPress site. They focus on aspects like loading speed, image optimization, and overall website functionality.
  • Who Should Use WordPress Optimization Plugins?
    Everyone who wants to improve their site’s speed, search engine ranking, and user experience, including bloggers, businesses, and eCommerce sites, will find these plugins particularly useful.
  • Why Are Optimization Plugins Important for WordPress Sites?
    They can contribute to improving site speed and performance, which are key factors in user satisfaction and SEO rankings. Faster sites usually offer a better user experience and can rank higher in search results.
  • How Do Optimization Plugins Improve Website Speed?
    They can compress images, minify CSS and JavaScript files, and implement caching, which can significantly reduce page load times.
  • Can Optimization Plugins Affect My Website’s SEO?
    Yes, positively. Faster loading times and better user experience, both of which can be achieved through optimization plugins, are important factors for SEO.
  • Do I Need Technical Skills to Use These Plugins?
    Basic optimization settings can usually be managed without advanced technical skills. However, some plugins offer more in-depth features that might require some technical knowledge.

The post 6 Best WordPress Plugins to Optimize & Speed Up Your Website appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/wordpress-speed/feed/ 0
How to Speed up Google Fonts in WordPress https://speckyboy.com/speed-google-fonts-wordpress/ https://speckyboy.com/speed-google-fonts-wordpress/#comments Sat, 02 Nov 2024 11:49:04 +0000 https://speckyboy.com/?p=86422 In this quick tutorial, we show you a couple of methods for optimizing and drastically speeding up Google Fonts in WordPress.

The post How to Speed up Google Fonts in WordPress appeared first on Speckyboy Design Magazine.

]]>
Today, I’m going to cover a few methods for optimizing and speeding up Google Fonts in WordPress. Images, of course, are and always will be the heaviest part of a web page, but according to HTTP Archive, as of October 2016, web fonts are just over 3% of an average page’s overall weight.

Even though the weight of web fonts makes up only a small portion of the overall web page, every optimization you make helps contribute to faster load times. Check out some ways below to speed up those fonts!

What are Google Fonts?

First off, for those of you who might not know, Google Fonts is an open-source (free) directory of over 800 web font families which you can use on your website. They are also available to download locally for print and other uses. Millions of WordPress websites utilize Google Fonts as it is a great free way to enhance the look and usability of your site.

If you are going for pure performance, system fonts will always win, but there is nothing like the professionalism and aesthetic of a good web font. And in fact, typography has been shown to affect conversions in a positive way. But everything has its cost. And so, it is important to understand how adding Google Fonts to your WordPress site affects speed and performance.

How to Use Google Fonts in WordPress

There are a couple of ways to add Google Fonts to your WordPress site. The first and default way is to grab them directly from Google. This method uses their global CDN to deliver the fonts quickly from different servers from around the globe.

When you add them to your site there will be an external request to fonts.googleapis.com.

googleapis

The are also external requests to fonts.gstatic.com for the WOFF or WOFF2 versions depending upon browser support.

gstatic

WordPress Plugin

If you are a WordPress beginner, the easiest way to add Google Fonts to your website is probably with a free plugin. The Easy Google Fonts plugin is a good popular example. As of writing, it currently has over 300,000 active installs with a 4.9 out of 5-star rating.

easy google fonts wordpress

Add Embed Code From Google Fonts

It is important to note that most WordPress plugins add slight overhead, and so I prefer to add Google Fonts with their much simpler to use embed code. So, head over to Google Fonts and choose the font you want. For this example, I’m using Roboto.

Click on the “Customize” option. This is an important step as each font family has different font weights. Typically you will want regular, medium, and bold.

Note: Every font-weight you include adds to the overall load time of your fonts, so don’t just select all of them. The less, the better.

4 roboto google fonts

Then click on the “Embed” option. This is where you will want to copy the embed code it provides.

google fonts embed

Take that code and put it into the <head> section of your WordPress site. There are different ways you can do this, some might prefer to enqueue the fonts, but for this example I simply added the code to the header.php file. Note: This might vary slightly depending on the theme you are using.

header font embed

Then, to actually make your WordPress theme use the Google Fonts, you have to add some CSS styles. Below is an example of what I’m using. If your theme admin panel doesn’t have a custom CSS editor you can always use a free plugin like Custom CSS and JS.

body {font-family:roboto; font-size:18px;}
h1,h2,h3,h4,h5,h6 {font-family:roboto; font-weight:700; text-transform:none !important;}
h1 {font-size:28px;}
h2 {font-size:26px;}
h3 {font-size:24px;}
h4 {font-size:20px;}
h5 {font-size:18px;}
h6 {font-size:16px;}

Now that you know some quick methods for adding Google Fonts to your WordPress site, I’m now going to do a few quick tests to see alternative ways of speeding them up. I ran some tests first with the setup above and the average speed came out at 418ms. Note: Each test was run five times, and the average result was taken.

google fonts cdn speed test

Host Google Fonts Locally

Another way to deliver Google Fonts on your WordPress site is to host them locally on your web server. If your audience is in a certain geographical location and close to your server, it can actually be faster to host them locally than it is to use Google Fonts. Google Fonts CDN is great, but adding those additional external requests and DNS lookups can cause delays.

This method will typically only work if you are using fast hosting. In the example, I’m using managed WordPress hosting from Kinsta, which is ironically powered by the Google Cloud Platform.

To host locally I actually utilized a free tool called the google-webfonts-helper. This allows you to download the Google fonts locally more easily and gives you all of the CSS. Below is an example of what we will end up with. You will need to upload the fonts you downloaded to your web server. In this case, I put them in a folder called “fonts.”

/* roboto-regular - latin */

@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  src: local('Roboto'), local('Roboto-Regular'),
       url('https:/perfmatters.io/fonts/roboto-v15-latin-regular.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://perfmatters.io/fonts/roboto-v15-latin-regular.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

/* roboto-500 - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 500;
  src: local('Roboto Medium'), local('Roboto-Medium'),
       url('https://perfmatters.io/fonts/roboto-v15-latin-500.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://perfmatters.io/fonts/roboto-v15-latin-500.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

/* roboto-700 - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 700;
  src: local('Roboto Bold'), local('Roboto-Bold'),
       url('https:/perfmatters.io/fonts/roboto-v15-latin-700.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://perfmatters.io/fonts/roboto-v15-latin-700.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

We then need to make sure to remove the embed code from Google Fonts in the header so that you no longer have those external calls. I then again ran some tests with the setup above and the average speed came out to 386ms.

local google fonts speed test

Note: The web server is located in Iowa, and the speed test from Pingdom was run from Dallas, TX. So as you can see, even though the server is located elsewhere in the United States, it is still slightly faster to load Google Fonts locally on the server. Of course, you will want to test various locations yourself based on your own audience.

Host Google Fonts on Your Own CDN

Now for a third scenario. On the site above, I’m using a third-party CDN provider already (KeyCDN) to host all of the other assets(images, CSS, Javascript, etc.). What happens if we now throw our fonts on the same CDN, instead of Google’s CDN?

I’m using the free CDN Enabler WordPress plugin. This actually copies the fonts from the “fonts” folder on the web server to KeyCDN automatically. We then have to tweak the code slightly so that the path to the fonts is now pointing to the CDN (such as cdn.domain.com).

/* roboto-regular - latin */

@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  src: local('Roboto'), local('Roboto-Regular'),
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-regular.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-regular.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

/* roboto-500 - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 500;
  src: local('Roboto Medium'), local('Roboto-Medium'),
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-500.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-500.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

/* roboto-700 - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 700;
  src: local('Roboto Bold'), local('Roboto-Bold'),
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-700.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
       url('https://cdn.perfmatters.io/fonts/roboto-v15-latin-700.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}

I then again ran some tests with the setup above and the average speed came out to 384ms.

As you can see, using a CDN is yet again just slightly faster. Not by much, but if you compare it to Google’s CDN, test it, it definitely is faster. Part of this is because it can utilize the same HTTP/2 connection, and it still reduces the external call and DNS lookup, just as hosting locally does. And of course, one advantage to this method is that it will be globally faster.

Summary

As you can see from the tests above, the Google Fonts CDN is great, but it might not always be the fastest. Of course, it will always depend on your own environment and where you are serving up traffic, whether it be to a local audience or global.

I recommend testing each method above for yourself and see which one is the fastest and works the best for your WordPress site. And remember, only load the font weights you actually need!

The post How to Speed up Google Fonts in WordPress appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/speed-google-fonts-wordpress/feed/ 11
How to Analyze & Speed Up Your Website https://speckyboy.com/analyze-speed-website/ https://speckyboy.com/analyze-speed-website/#comments Sat, 11 Feb 2023 20:39:32 +0000 https://speckyboy.com/?p=97753 We show you how to analyze your website and carry out simple changes that will, in most cases, speed up a slow-loading website dramatically.

The post How to Analyze & Speed Up Your Website appeared first on Speckyboy Design Magazine.

]]>
Having your website load pages quickly and efficiently is more important than ever, not just from the standpoint of ranking higher in search engines but also from a user experience point of view.

Back in 2006, Amazon published information showing that for every 100 milliseconds faster their website got, their revenue increased by 1%. Recent Google data also indicates that users will spend 70% more time on your site if it loads in under 5 seconds.

Here I will show you how to analyze your website and carry out a few common and simple changes that will, in most cases, speed up a slow-loading website dramatically and have users spending more time on your site as well as search engines favoring your fast loading website.

Tools For Analyzing Your Page Speed

There are a number of free to use tools out there to check over your pages and determine what’s slowing them down. These three, in my opinion, are the most popular and easy to use:

Pingdom, although it provides less information than the other two tools, the information it does offer is some of the most important, and the corrections it shows, if corrected, will show some of the most immediate speed improvements to your pages.

GTMetrix is similar to Pingdom but shows much more information on how you can potentially speed up your pages. I generally use this after Pingdom, if my pages are still loading slowly or if I feel I can get more speed out of them.

Google PageSpeed Insights, I find it to be less important as the changes it recommends after using the other tools only ever really improve speeds by a small amount, if at all, but it’s still a useful tool for improving your pages.

Don’t Get Hung Up on a Perfect Score

With all three tools, it’s important not to get hung up on the scoring system and set out on a quest for the absolute perfect score. The main thing is to identify the main problems and correct them to reach the optimum page speed you are looking for.

This is especially true for Google PageSpeed Insights, as people commonly think that having a high Google page speed directly influences their search engine ranking position, which is not the case.

Analyzing Your Web Pages Using Pingdom

To get started, simply go to Pingdom, enter your web page URL, choose a server closest to your location and click on “Start test.”

Once it has analyzed your page, you will be shown information such as a total page score along with how long it took to load and a breakdown of the things you can fix to speed the page up.

Pingdom Speed Test results

How to Speed up the Pages

Now that you know what’s causing the slow page speeds, it’s time to fix the suggested problem areas. There are a whole range of suggestions that may come up. I will only be able to cover a few of the most common problems, which should show immediate improvements to your web page’s loading times.

Nearly all of the problems that arise are pretty simple to fix, even for a novice. Information on how to fix each one, that I’ve not covered here, can be found with a simple web search.

Leverage Browser Caching

Browser caching essentially works by telling the user’s browser to request the web page’s resources from the browser, instead of from the web server.

Although this won’t speed up the site for new visitors, it will drastically speed up your pages for returning visitors. To do this, you must add a few lines to your .htaccess file.

Your .htaccess file can be found in the root folder of your website. If you do not have one, simply create a text file, add the code below and save it as .htaccess within the root of your website.

More detailed information can be found here.

## EXPIRES CACHING ## ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/pdf "access plus 1 month" ExpiresByType text/x-javascript "access plus 1 month" ExpiresByType application/x-shockwave-flash "access plus 1 month" ExpiresByType image/x-icon "access plus 1 year" ExpiresDefault "access plus 2 days" ## EXPIRES CACHING ##

Merge, Minimize and Move Resources

Merging your JavaScript and CSS files into as few files as possible, as well as minimizing them, will allow them to be loaded faster. Also, moving the files below the fold so that the page content loading isn’t held up waiting for the JavaScript files to load will also improve speed.

Remember when merging JavaScript and CSS files into single files to make sure they are in the correct order. You can use the browser’s inspector to check the order that the files are loaded, then go through each file, copying the code and pasting the code into the single file.

This will ensure, for example, that JavaScript functionality such as jQuery is loaded before any JavaScript functionality that relies on jQuery. The same applies to CSS, to ensure rules that are supposed to overwrite other CSS rules are applied properly.

If the single files become too large, you can break them up into multiple files. However, try to keep the files to a minimum. Once you have your final files, minimize them and save them. Then replace all the old references to them in your HTML with the new files.

For the JavaScript files, add the script tags that reference the files to the bottom of the HTML before the closing body tag.

Use a CDN for Your Resources

Loading static resources from a CDN can correct a couple of speed issues. This will allow your page to load while the browser fetches the content from another domain. This also allows you to fix the “Serve content from a cookieless domain” problem you may run into if your website is using cookies.

You can use CDN providers to serve your content. However, it’s easy to create your own CDN to serve your content. To do this, make sure your CSS, JavaScript, or image files are in a separate folder from the other files on your website. Then you create a subdomain to point directly to the folders.

For example, for serving CSS, create a subdomain called csscdn.yourwebsite.com and point it directly to your CSS folder within your website.

Then on the front end, instead of referencing the CSS files using /css/styles.css, you use csscdn.yourwebsite.com/styles.css. You can do the same for your JavaScript, images, and any other resources to reduce the loading times of your page.

Compress Your Images

These days image compression can be done without much, if any, noticeable loss of quality. There are a range of image compression techniques out there to use, including WordPress plugins and scripts that can compress your images upon upload, automatically.

For manually compressing images, there is a free to use tool called Tinypng where you simply drag your images onto the page, it compresses the images, and you can then download the compressed versions.

Compressing all your files can significantly increase the loading speed of your page. Tinypng is able to compress a 57KB image into a 15KB image without any noticeable quality difference at all. If your web page has large images or displays many images, just compressing all the images alone will make your page load in a fraction of the time.

If you are not already familiar with Gulp or Grunt, then you should seriously consider adding them to your web development toolset as they are both great for automating tasks such as JavaScript and CSS minification, image compression as well as a whole range of other, extremely useful tasks.

The post How to Analyze & Speed Up Your Website appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/analyze-speed-website/feed/ 1
Skyrocketing WordPress Speed: The Ultimate Guide To WP Fastest Cache https://speckyboy.com/wp-fastest-cache/ https://speckyboy.com/wp-fastest-cache/#respond Sun, 22 Dec 2019 23:22:43 +0000 https://speckyboy.com/?p=98511 WP Fastest Cache is a versatile plugin that helps decrease the page load time of your website by creating quickly rendered HTML files that are stored and accessed by subsequent...

The post Skyrocketing WordPress Speed: The Ultimate Guide To WP Fastest Cache appeared first on Speckyboy Design Magazine.

]]>
WP Fastest Cache is a versatile plugin that helps decrease the page load time of your website by creating quickly rendered HTML files that are stored and accessed by subsequent visitors.

Since a WordPress website is rendered through PHP and MySQL it requires RAM and CPU usage each time the page is requested from the server. This slows down the load time and places more effort on the user’s computer or device, as well as the database. However, with a cache system, the page is rendered one time and then stored as a static HTML file, thereby reducing the load time for each new visitor.

How WP Fastest Cache Works

After installing the plugin, start digging into the customization settings by clicking on the WP Fastest Cache link in the menu bar.

This directs you to the Options page, where you will really begin to utilize the plugin’s features. We will focus on each one of the tabs in the option menu.

1. Starting with the first tab, Settings, we will start implementing the caching system. Check the first box, Enable, to allow the plugin to start working on your site.

2. The next option, Widget Cache, is grayed out, which means it is not available in the free version of the plugin, in order to use any of the premium options, you will need to upgrade to the paid version. We will focus on the free options in this tutorial.

3. The Preload option will generate the page caches automatically, instead of when someone visits the site. Choose which features you want to automatically cache and click OK.

4. The next option allows you to block the cached version for logged-in users and will cause the page to load naturally.

5. After that, we’re also given the option to block the cached desktop page when someone accesses the site from a mobile device.

6. The subsequent Mobile Theme would allow you to cache the mobile version, but is available only to those who purchase the premium version.

7. New Post allows you to choose which cache files to clear when new content is published on your website.

8. Similar to the previous option, Update Post allows you to choose which cache to clear when content is updated on your website.

9. Minify HTML allows you to decrease the amount of HTML that composes your cache file, thereby also decreasing the load time for your visitor.

10. Minify CSS actually decreases the size of your CSS files to make page rendering faster.

11. Combine CSS will integrate multiple CSS files into one file in order to reduce the number of HTTP requests and decreasing load time.

12. As with the CSS, the Combine JS option will combine multiple JavaScript files into one file for fewer requests from the server.

13. Gzip compresses the size of files and resources being sent from the server, allowing them to load faster.

14. Browser Caching enables frequently used files (such as CSS and images) to be stored in a visitor’s web browser so the resources will not have to load each time the visitor views the page.

15. The last option on this page is Language. This will only change the language in which the options menu appears for this plugin, not for your site as a whole.

Choose Turkish, for example. Only the words contained in the plugin’s options pages will be changed.

English is the default. Make your selection from the dropdown menu, then click Submit to save the changes you’ve made on this page. You’re well on your way to optimizing your site with a cache system.

Next, let’s check out the second tab in the menu. Delete Cache.

Delete Cache

The grayed out features are only for premium subscribers, but the two main options at the bottom are still available.

  1. Click on Delete Cache to delete every cached file.
  2. Choose Delete Cache and Minified CSS/JS to delete all caches as well as the minified CSS and JS files created in previous options. The minified versions of CSS and JS are kept in a separate file on the server that the rest of the cache, so choose this second option to delete those as well.

That’s it for this tab. Not bad, right? Let’s move on to the next tab, Cache Timeout.

Cache Timeout

1. In this tab, we have the chance to create Timeout Rules. Click Add New Rule to bring up an options box.

The first option in the box is If REQUEST_URI. Click to view a dropdown menu with four choices: All, Home Page, Starts With, and Is Equal To. Choosing All will cover every URI requested by visitors, while the following three options will limit the timeout rule to either the Home Page or a URI Starting With or Equal To the value you type in the text box next to the menu.

Once you have chosen the URI type, choose what happens Then from the dropdown menu. The options in this box are for the time period in which the cache is deleted.

Choose how frequently the cache should be timed out, and then click Save. You will see your new timeout rule appear.

Create as many rules as you want in order to cover different areas of your website. Choose the type of URI (whether homepage or starting with a specific URL) and choose the frequency in which the cache is deleted for that area.

Great, that was the Timeout Rule section. Let’s move on to the next tab. Notice that Image Optimization and Premium contain content only available to premium subscribers.

We will move on to the Exclude tab. The first option here is to exclude certain pages from being cached.

Exclude

1. Notice there are two default rules to exclude the wp-login.php and wp-admin pages. These cannot be edited or deleted.

2. Click Add New Rule to create a new rule.

3. Select the type of page, content or URI you would like to exclude, and click Save.

4. You will see your new exclusion rule appear. Any rules you create can be edited or removed by clicking on them.

5. The next section to which you can add rules is the Exclude User-Agents area. Again, notice two default rules that cannot be changed or removed. Choose Add New Rule to define a rule.

This option allows you to create a rule that excludes caching for a certain type of user agent. Type your content and click save.

6. The last three options allow you to exclude specific cookies, CSS or Javascript. Use these in the same way by clicking Add New Rule, choosing the excluded URI and saving the changes.

You should now have a good handle on the types of files that are being cached, minified or combined, as well as how to exclude certain types of pages, content or user agents from utilizing the cache system.

CDN

Of the two tabs left to explore, one is available only to premium subscribers. So, we will take a brief look at the last tab we can utilize. Click on the CDN tab.

In a nutshell, CDN, or Content Delivery Network, is a system of storing your cached files in different geographic locations to minimize the amount of time it will take for a website user in another country to access the files.

There are different CDN providers which can help deliver your content speedily. If you have an existing account with any of the providers listed above, click on it to get set up. If not, it’s easy to create an account with MaxCDN to get started using this additional feature.

The post Skyrocketing WordPress Speed: The Ultimate Guide To WP Fastest Cache appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/wp-fastest-cache/feed/ 0
Why You Need to Prioritize PageSpeed in Discussions with Clients https://speckyboy.com/prioritize-pagespeed/ https://speckyboy.com/prioritize-pagespeed/#comments Sat, 18 Nov 2017 20:22:06 +0000 https://speckyboy.com/?p=97060 For the past few years, small and medium businesses (SMBs) across the world have been told that making their websites mobile-friendly, and embracing a mobile-first world, were essential for business...

The post Why You Need to Prioritize PageSpeed in Discussions with Clients appeared first on Speckyboy Design Magazine.

]]>
For the past few years, small and medium businesses (SMBs) across the world have been told that making their websites mobile-friendly, and embracing a mobile-first world, were essential for business success. And that was good advice.

However, now that many SMBs have accepted these truths and made their sites responsive in design, what is the next big challenge the web design industry will face in building websites for this audience?

According to Google and findings of our own, it’s going to be pagespeed.

Look at it like this: pagespeed is already something you think about subconsciously as you create new websites. You’re careful about how many plugins you install as well as the quality of themes you use to build clients’ websites, among other things. But now it’s time to put pagespeed (especially as it pertains to the mobile experience) front and center in your work as well as in the conversations you have with clients.

Of course, this isn’t going to be easy, so the following guide will give you the tools and information you need to properly position pagespeed as the next “must have” with your clients.

Step 1: Start with Google

Let’s face it: when it comes to proposing what needs to be done to a website, your clients aren’t necessarily going to listen just because you say “you must do this because I’m telling you to”. If you want to be smart about this, then you should name-drop Google first. Everyone knows the name. Everyone trusts their authority. And no one is going to question what Google says has to be done.

So, here is how you can use Google to position pagespeed as a top priority in web development:

Point 1 – For starters, show them how Google made updates to their search algorithm back in 2010 to include pagespeed as a ranking factor.

Point 2 – They then were kind enough to give us the PageSpeed Insights testing tool so we could do our own website assessments. These tests include not only an assessment of the desktop site, but the mobile site too.

Point 3 – Next on the horizon is mobile-first indexing. When this launches, Google intends on adding pagespeed to the ranking factors as they don’t believe enough marketers or business owners are taking this seriously enough. How do you know this?

Point 4 – Well, according to Google, 53% of their mobile users abandon a website because they didn’t want to wait more than three seconds for a page to fully load. And since the average mobile page loading speed is 22 seconds… Let’s just say that the state of mobile speed optimization is not good.

Okay, so why should Google even care if a business’s site is optimized for mobile loading?

Well, it’s because the success of its search engine rides on its ability to recommend relevant and quality search results to its users. With pagespeed becoming ever more important, Google needs to include this consideration as part of its ranking criteria. This ensures that users receive the best experience from the search engine because they had a good experience visiting the recommended site on mobile. And the happier they are with search results, the more they’re going to use Google.

Google has had their eyes on pagespeed for a long time, so small and medium businesses absolutely need to get with the program now. If they’re not willing to do it to improve the user experience alone, then explain that this is about being justly rewarded by the search engines for playing by their rules.

Step 2: Present Them with the Facts

When responsive design first became a “thing”, your clients were likely confused about what that meant until you showed them a real working example of it. Even then, they probably needed further explaining as to why it mattered, especially if it meant more work for you and more money they needed to spend on it.

Business owners don’t think the same way we do. For them, it’s not about “user experience” and “responsive design”. Their ears are listening for “more conversions” and “higher engagement rates”. At the end of the day, they’re concerned with their bottom line and they want to make choices for their business that will lead them down the path to more money.

So, you’ve got to break it down into a language they understand.

Let’s start with what Google says about why mobile speed matters.

Faster loading times on your site will lead to higher rankings in search–which is what you want. But this is as a result of how pagespeed affects the user experience and, in turn, your engagement and conversion rates. Google found that faster pagespeeds lead to:

  • 70% longer sessions for visitors who encountered a page that loaded in 5 seconds as opposed to 19.
  • 35% lower bounce rates.
  • 60% increase in pageviews with every visit to the site.

What it boils down to is this: 77% of websites load within ten or more seconds on mobile devices. If your clients’ sites fall into that category, they’re looking at a 7% drop in conversions for every additional second they force their users to wait.

At Duda, we found similar results when examining data pertaining to the relationship between the render start time and mobile engagement rate.

This trend also holds true when just looking at Click-to-Call.

What this means is that sites with the fastest render starts (less than one second) get nearly 50% more engagement than sites that take the longest to load (between three and four seconds). As you can see from the data, there is roughly a 10% decrease in conversion rate for every additional second it takes a site to load.

Step 3: Have a Plan of Attack for Dealing with Pagespeed

Okay, so we know that pagespeed is going to be the next battlefield with clients. You now have Google’s backing as well as statistical data to show them why pagespeed is so important. But that’s not enough.

Let’s say your clients are gung ho and ready to get moving on optimizing their sites for pagespeed. This is not the time to throw you hands in the air and say, “Don’t look at me!” Nope, you need to have a solution ready to roll here. You are the pagespeed optimization expert and this plan will be proof of it.

Google has clearly laid out what needs to be done in order to optimize a website (mobile or otherwise) for speed:

  • Implement browser caching
  • Remove landing page redirects
  • Minify HTML, CSS, and JavaScript
  • Compress and optimize images
  • Prioritize above-the-fold visible content

You can verify that you’ve done all this by using Google’s PageSpeed Insights tool.

The next step in your plan then requires that you find a reliable partner to provide you with the tools to create mobile-friendly and fast websites without issue.

If you weren’t aware, Duda has addressed this issue head on. They have reconfigured the way Duda websites are coded to ensure they adhere closely to Google’s best practices for load times, as recommended by Google’s PageSpeed Test. Duda websites now regularly score in the high 80s and 90s in Google’s test.

Not only does this news mean that Duda websites now load faster than ever (which is great for your existing customers), a strong Google PageSpeed score is also a great marketing and sales tool for your company. Couple that with the statistics that demonstrate the real power of having a website fully optimized for speed, and you may find yourself overwhelmed with new clients dying to work with you.

The post Why You Need to Prioritize PageSpeed in Discussions with Clients appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/prioritize-pagespeed/feed/ 3
Website Speed Part 4 : PHP Programming for Speed https://speckyboy.com/website-speed-part-4-php-programming-for-speed/ https://speckyboy.com/website-speed-part-4-php-programming-for-speed/#comments Mon, 12 Mar 2012 09:00:34 +0000 http://speckyboy.com/?p=20300 Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to...

The post Website Speed Part 4 : PHP Programming for Speed appeared first on Speckyboy Design Magazine.

]]>
Programming for speed is not what most coders think of. What they tend to consider first, and usually only, is getting it working. Sometimes people will talk of refactoring to reduce the amount of code, but again this is usually only for those that suffer with the luxury of having too much money and time.

I wish I had that luxury, to be able to spend twice as long on a problem to make a perfect solution. In truth I don’t most of the time, as I am out there getting new clients, making other products or not in the fortunate position to have a client with very deep pockets.

To counteract these things I have a bunch of methods stored in my head that allow me to choose the best path first time (I hope!). I am going to share these best practices with you so you can maybe do the same, maybe even better. If you have any great speed suggestions for coding, please comment and I will append it to this post.

Also, please note that this is not an exhaustive list. This is more of a pointer to things you should consider in your favorite coding language. Although this is for PHP specifically, I’ve tried to keep it as generic as possible to make it possible for all coders, no matter the language, to benefit.

Making IF ELSE smaller

IF is possibly the most used statement from all the programming languages, and I think the most used by a noob programmer (hey I was one once, I remember my code).

Common IF ELSE usage


  if ( $something == true ){
  $value = 'yes';
  }else{
  $value = 'no';
  }

Now using only IF


  $value = 'no';
  if ( $something == true ){
  $value = 'yes';
  }

As you can see all that has been done is that value is pre-set to ‘no’ and only gets changed to ‘yes’ if something is true. Both bits of code have the same outcome, one has less code.

If you only have 1 command inside the if statement then you can take things a little further. PHP does not require that you have the curly brackets when there is just one line.


  $value = 'no';
  if ( $something == true )
  $value = 'yes';

Ternary operators

We can go a stage further and have Ternary Operators. These are mathematical instructions that allow for a yes/no answer, just like IF.

IF presented as ternary operation


  $value = ( $something == true ) ? &quot;yes&quot; : &quot;no&quot; ;

Again the same IF ELSE statement, made much smaller. What it does is check the if the statement inside the brackets is either true or false, if it is true it will set value to be “yes”, if it is false it will set value to be “no”

syntax of ternary operators


  output = ( true/false condition ) ? true-value : false-value ;

It is not essential to have an output, as the true or false value could call a function and not return a value.

Using Range to create an array of numbers

Often people will code an array with just a bunch of numbers in it so that they can loop through it.

PHP code to create a select drop down list


  // selected item value
  $item = 12;
  // create array of numbers
  $array_of_numbers = array( 2,4,6,8,10,12,14,16 );
  // start the select 
  echo &quot;&lt;select name='myselect' &gt;&quot;;
  foreach ($array_of_numbers as $number){
  // use terany operator to compare $number and $item, if the same make $selected = &quot;selected&quot;
  $selected = ( $number == $item ) ? &quot;selected&quot; : &quot;&quot; ;
  // echo option, with details filled in
  echo &quot;&lt;option value='&quot; . $number . &quot;' &quot; . $selected . &quot; &gt;&quot; . $number . &quot;&lt;/option&gt;&quot;;
  }
  echo &quot;&lt;/select&gt;&quot;;

Now the same thing shorter with range


  // selected item value
  $item = 12;
  // start the select
  echo &quot;&lt;select name='myselect' &gt;&quot;;
  foreach ( range(2,16,2) as $number){
  // use ternary operator to compare $number and $item, if the same make $selected = &quot;selected&quot;
  $selected = ( $number == $item ) ? &quot;selected&quot; : &quot;&quot; ;
  // echo option, with details filled in
  echo &quot;&lt;option value='&quot; . $number . &quot;' &quot; . $selected . &quot; &gt;&quot; . $number . &quot;&lt;/option&gt;&quot;;
  }
  echo &quot;&lt;/select&gt;&quot;;

Range is a really handy thing, as what it does is created an array of numbers (integers). It has the following syntax in php:


  range($start_number, $end_number, $increment);

The only needed compulsory items are the start and end number, the increment defaults to 1, but can be any number you like.

A range function is available in most languages but is unfortunately not available in Javascript out of the box, so to make this same saving in code you would be best to use a FOR loop

FOR loop version


  // selected item value
  $item = 12;
  // start the select
  echo &quot;&lt;select name='myselect' &gt;&quot;;
  for($number = 2; $number &lt;= 16; $number = $number + 2){
  // use ternary operator to compare $number and $item, if the same make $selected = &quot;selected&quot;
  $selected = ( $number == $item ) ? &quot;selected&quot; : &quot;&quot; ;
  // echo option, with
  echo &quot;&lt;option value='&quot; . $number . &quot;' &quot; . $selected . &quot; &gt;&quot; . $number . &quot;&lt;/option&gt;&quot;;
  }
  echo &quot;&lt;/select&gt;&quot;;

Turbo charging the FOR loop

Many people like to use a for loop as they believe that it is faster than a foreach. While this is often true, it does not offer the flexibility of foreach and with the wrong programming techniques can be slower

The slower FOR loop


// some text as a string
$text=&quot;We love SpeckyBoy&quot;;
// loop through all the characters
for($i=0; $i &lt; strlen($text); $i++){
// look for the o in the text string at the position of $i using a ternary operator
// echo true or false value as needed
echo ( substr($text,$i,1) == 'o' ) ? &quot;its an o&quot; : &quot;no o here&quot;;
}

The faster FOR loop


// some text as a string
$text=&quot;We love SpeckyBoy&quot;;
// get the length of the string
$length = strlen($text);
// loop through all the characters
for($i=0; $i &lt; $length ; $i++){
// look for the o in the text string at the position of $i using a ternary operator
// echo true or false value as needed
echo ( substr($text,$i,1) == 'o' ) ? &quot;its an o&quot; : &quot;no o here&quot;;
}

The 2nd for loop is faster as it does not need to re-check the string length each time the loop runs. The first loop will check the string length 17 times with the text used

Making your code easier to maintain, and faster

I often see the same problem with my noob code when I re-visit it. The code is all written on 1 line and very long. Check this bit of code as an example:


  $html = &quot;&lt;input name='&quot; . $name . &quot;' id='&quot; . $id . &quot;' value='&quot; . $value . &quot;' class='&quot; . $theclass . &quot;' type='checkbox' &quot; . $checked . &quot; /&gt;&quot;;
  echo $html;

It works just fine, and will be ok for any implementation, but there are some problems with it. For example if the class is empty, it is wasteful to code the empty class setting. While this may not make so much difference to a Javascript implementation, as this is being generated on the server with PHP, you’d be sending extra bytes to the clients browser which are not required. This of course will make the most difference when making AJAX calls and waiting for the reply, where extra bytes can make much more of an impact.

An easier way to maintain


  $attributes = &quot; name='&quot; . $name  . &quot;' &quot;;
  $attributes .= &quot; id='&quot; . $id  . &quot;' &quot;;
  $attributes .= &quot; value='&quot; . $value  . &quot;' &quot;;
  $attributes .= ($theclass != '' )?  &quot; class='&quot; . $theclass  . &quot;' &quot; : &quot;&quot; ;
  $attributes .= ($selected == $value )?  &quot; checked &quot; : &quot;&quot; ;
  $html = &quot;&lt;input type='checkbox' &quot; . $attributes  . &quot; /&gt;&quot;;
  echo $html;

As you can see, much easier to read, much easier to maintain, and used on the server side will produce less HTML code.

Don’t echo every line only the final output

It’s much easier to echo every line, or pass control back to HTML, than it is to write every line to a variable, yet writing the output to a variable first and only echoing at the end is the faster way to process

The easy way to do things, with a few variations


echo &quot;&lt;h2&gt;&quot; . $title . &quot;&lt;/h2&gt;&quot;; ?&gt;
&lt;small&gt;&lt;?php echo date(); ?&gt;&lt;small&gt;

The more server friendly way to do things

$output = &quot;&lt;h2&gt;&quot; . $title . &quot;&lt;/h2&gt;&quot;;
$output .= &quot;&lt;small&gt;&quot; . date() . &quot;&lt;small&gt;&quot;;
echo $output;

OK, this is a very simplistic example of what you should do as it is only 2 lines and then output.

Rounding up

This is a very short list of things to help make your PHP coding faster and easier to maintain. There is of course many more things that you can do to reduce the amount of code that you do use, or the speed that it runs at.

Most of these techniques can be taken across to other programming languages, so when your coding in Javascript or .NET give it some thought and you will be making things much faster.

More from the Website Speed series…

Website Speed Part 1: Write More Efficient CSS →
Website Speed Part 2: Working With and Optimizing Images for the Web →
Website Speed Part 3 – Caching WordPress →

The post Website Speed Part 4 : PHP Programming for Speed appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/website-speed-part-4-php-programming-for-speed/feed/ 22
Website Speed Part 3 – Caching WordPress https://speckyboy.com/website-speed-part-3-caching-wordpress/ https://speckyboy.com/website-speed-part-3-caching-wordpress/#comments Wed, 14 Dec 2011 00:09:42 +0000 http://speckyboy.com/?p=18422 As so many people have it installed, I thought I would share with you a key techniques integral to caching WordPress that will help your website speed. W3 Total Cache...

The post Website Speed Part 3 – Caching WordPress appeared first on Speckyboy Design Magazine.

]]>
As so many people have it installed, I thought I would share with you a key techniques integral to caching WordPress that will help your website speed.

W3 Total Cache is a dream plugin for achieving caching, I would recommend it to anybody. Yet there are times when you do not want to cache a whole page for long periods, but to cache sections of it so that a page rebuild is not as costly in server time.

For example I had a site where they did not want caching on the homepage as a whole as they wanted to have the following features:

  • Rotating background image provided by PHP.
  • Alternating advertising scripting for comparison of suppliers.
  • A loop that updates every 5 minutes, along with others that updated hourly.

It was chosen that a “sub caching” (to use the customers preferred term) strategy would be best. Now you understand the scene of what we need to achieve, a cached homepage which could have items within it updated regularly, that did not use the page cache of W3TC.

To achieve all of what the client wanted, I needed to use the Transients API for WordPress.

WordPress Transients API

The WordPress transients API is a simple set of three commands that work very much like Options API, but when a timer that you set runs out, the transient is automatically deleted. Inside a transient you can save any kind of data you like. It can be an array, object or just some text, it really does not matter what you store in there as WordPress takes care of it by serializing it as necessary.

What the Transients API also does is automatically save the transient in the quickest responding place on the server. This could be in the database, on the disk or in memcache depending on your servers configuration.

Here is the basic syntax for getting and setting a transient:

<?php
$value = get_transient( 'value' );
if ( false === $value ) {
        // if transient not set, do this!

        // create the data that needs to be saved.
        $value = 1;

        // save the newly created transient value
        // 60 seconds * 60 minutes * 24 hours = 1 day
        set_transient('value', $value, 60*60*24);
}
?>

Notice how they work in tandem with each other. If there is nothing set in the transient called ‘value’ then the code knows to set a new ‘value’ from the code inside the if statement.

As you can see, all we do to set a transient is use set_transient() with the name of the transient, in this case ‘value’, with it’s $value being the data you want to save, and the last part being the calculation that would created the number of seconds that the transient should last for.

Using Transients on a Single Loop Inside WordPress

Unless you are an ultra busy site with 100’s of content creators, you can be pretty sure that the loop that shows your posts in your blog does not change that often. Be that days or only minutes, caching will speed up the loop, as the server will not have to ask any complex SQL queries, but a simple single request to get the pre-found data, a much quicker and less intensive thing to do.

<?php
$loop = get_transient( 'loop' );
if ( false === $loop ) {

       // Show the last 100 tweets from the custom post type tweets.
       $query = array('post_per_page' => 100,
                     'post_type' => 'tweets',
                     'post_status' => 'publish' ) ;

       $loop = new WP_Query($query);

        // transient set to last for 1 hour
        set_transient('loop', $loop, 60*60);
}
// do normal loop stuff
if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post();

// show content or whatever you like
the_content();

endwhile;endif;

?>

The above query for the 100 tweets from the custom post type of tweets will now be saved inside the transient called ‘loop’

A Question of Data or Information

Using the above transient we are dealing with Data, or un-formatted information. This is all fine, and works just great, but you could take things a little further.

Instead of manipulating the data every time that the page is loaded, it can be better to add all of the HTML to the loop and then save it to the transient so that it is even quicker to load.

As shown in the below widget, all of the widget is built as a full HTML section before it is saved. This is my preferred method of implementation as there is less processing to do.

Caching Widgets with Transients

Many widgets show content that hardly ever changes, for example categories on the site, or pages on the site. It’s only really things like latest comments that tend to change often, and even then it’s doubtful that would be more than once per minute. So even with the more active widgets there is space for caching, let alone the sedentary ones.

If you have a busy site for some reason, that could be thousands of hits inside that minute that take up unnecessary processing time to check again and again all of the widgets and their output.

Caching widgets is pretty easy, here is an example widget for displaying a table of events from a custom post type called ak_events.

class show_ak_events_Widget  extends WP_Widget {
    function show_ak_events_Widget() {
            /* Widget settings. */
            $widget_ops = array( 'classname' => 'ak-events', 'description' => 'Shows events in a table' );
            /* Widget control settings. */
            $control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'ak-events' );
            /* Create the widget. */
            $this->WP_Widget( 'ak-events', 'Show Events', $widget_ops, $control_ops );
    }

    function widget( $args, $instance ) {
            extract( $args );
            // get cache if it exists
            //  $widget_id comes from the widget $args->widget_id and is the widgets unique ID
            $output = get_transient('events'.$widget_id);

            // if no $output do stuff inside this if statement
            if ( $output === false ) {
                 // set the title variable
                 $title = apply_filters('widget_title', $instance['title'] );

                // standard opening of widget
                $output = $before_widget;

                // if a title exists add it to the top of the widget
                $output .= ( !empty( $title ) )? $before_title . $title . $after_title : "" ;

                // Create query arguments for WP_Query to use
                $widgetargs =  array( 'posts_per_page'=>'-1',
                                       'post_type'=>'ak_events',
                                       'post_status'=>'publish'
                                       );

                // WP_Query sets up a loop query
                $query = new WP_Query( $widgetargs );


                // create the opening table and top row
                $output .= "<table><tr><th>Event Name</th><th>Information</th></tr>";

                // If the WP_Query has results send them through the loop
                if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
                    $output .= "<tr><td>" . get_the_title() . "</td><td> " . get_the_excerpt() . " </td></tr>";
                endwhile;endif;

                // close the table
                $output .= "</table>";

                // close widget properly
                $output .= $after_widget;

                // save $output as a transient and set it to be 60 seconds * 5 = 5 minutes.
                //
                set_transient( 'events'.$widget_id, $output, 60*5 );
            }

            echo $output;

    }

    function update( $new_instance, $old_instance ) {
            // save form data
            $instance = $old_instance;
            $instance['title'] = $new_instance['title'];

            // delete the transient so the new title setting is used
            delete_transient('events'.$this->id);
    return $instance;
    }

    function form( $instance ) {
         $defaults = array(
           'title'=>''
       );
        $instance = wp_parse_args( (array) $instance, $defaults ); ?>
         <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>">
                <?php _e('Title:','proving-ground'); ?>
            </label>
            <input id="<?php echo $this->get_field_id( 'title' ); ?>"
                      name="<?php echo $this->get_field_name( 'title' ); ?>"
                      value="<?php echo $instance['title']; ?>" style="width:95%" />
        </p>


        <?php
     }
}

As you can see, all of the loop and processing activity takes place inside the if statement that runs when the widget is called. The other thing to notice is that there is also delete_transient() used inside the update function to delete the transient every time you update the widget on the admin screen.

The bit that makes this work is really the ‘events’.$widget_id bit, as that assigns a unique transient name to each instance of the widget that is loaded. So the widget used in one sidebar is cached separately from the same instance of the same widget .

Using Caching for Theme Options

Theme options are more and more common inside WordPress themes. They hold things like the settings for the theme which are applied every time the site it loaded. This is fine, but it is requested from the database each time, as that is the way that get_option() works.

If you use get_transient() instead you might not be going to the database to request it. It’s possible it’s coming from memory cache or disk cache, which are quicker to access.

Here is a simple little function I made to manage this for me, whenever I need to get_option() I use my_get_cache_option() to get the WordPress option I want. The following code goes in your functions.php.

<?php
function my_get_cache_option($option_name = 'ThemeAdminOptions' ){
    // get wanted transient
    $value = get_transient( $option_name  );
    // check if it has any content
    if(false === $value){
        // if no content in the transient get new copy of wanted option
        $value = get_option( $option_name );
        // set new transient with a refresh of 1 day
        set_transient( $option_name, $value, 60*60*24 );
    }
    // return the transient $value or newly created $value
    return $value;
}
?>

Personally I setup default of ‘ThemeAdminOptions’ and use that for my theme options, but if I want to get a different transient or option I use it like this:

<?php
// get cached option
$options =  my_get_cache_option('WantedOptionName');
// do code with options array/object/string
// example code
echo $options['google_analytics_id'];
?>

If you are going to use this solution, don’t forget to use delete_transient() within the process of saving the updates on your admin pages. Normally you would just update the options, but as well as that you need to delete the transient that exists as your other code will pull the old data from the transient for up to 24 hours.

<?php
// update the option as normal
update_option('WantedOptionName', $value );

// delete the transient that may be set
delete_transient('WantedOptionName');
?>

Using Transients for Timed Events

One of the great benefits of the Transients API is the ability to setup very simple timed events that perform functions for you.

Say you wanted to get an RSS feed every minute from a stock trading company, it could be easily achieved by using the following function and call:

<?php

function setup_timed_event(){

    // get value if set;
    $value = get_transient('run_batch');

    // if not set run if statement;
    if($value === false){
            // run every time the timer runs out
            do_minute_batch();


            // set any value to $value;
            $value = 'done';

            // setup transient to last for 60 seconds;
            set_transient('run_batch', $value, 60);
    }
}

function do_minute_batch(){
 //
 // code to run in batch here that calls the RSS feed.
 //
}

//
// use an action to call the timed event every time the init is called. 
add_action('init','setup_timed_event');
?>

It is not strictly true that it will run every 1 minute, as if the server performs no activity of any description for more than a minute, it will not run, but will run on the next activity whatever that is.

Other Activities that can be Cached with Transients

The list is endless of things that you can make quicker on a website by using the transients API. Anywhere you have to process data, you can use it. If you write a twitter plugin, you could use it to save the Twitter feed and only update when it is deleted. Or maybe you have an Amazon store that you want to setup with caching for small periods, this is perfect and simple to use. In fact anywhere you need to get data from an external source, cache it with the transients API.

There is nothing to stop you taking caching to the nth degree with multi loops with differing cache timers based on importance of content, or make sure that every single widget you have caches for the right content lifetime. In fact there is nothing to stop you giving the caching timeout control to the widget administrator by having a field that is the number of seconds or the calculation that sets the time period of the widgets set_transient(). It really is endless where you can go with this.

What About Things that Echo to the Screen?

In WordPress there are quite a few things that automatically echo to the screen, such as the_content(). Sometimes you want to use these items rather than the get equivalent get command, i.e. get_the_content(), as the formatting is already good without the need for extra manipulation.

Or maybe a plugin developer has added an action or filter to the command, for example the_content() could also have an action or filter added to it that appends share links and icons to the end of the content.

Both of these examples call for a slightly different way of saving the data in to the transient. We now have to use an ob_start(),ob_get_contents(), ob_end_clean() combination to save the data we are echoing to the screen and then save that as a variable as the transient.

<?php
$loop_output = get_transient( 'loopOutput' );
if ( false === $loop_output ) {

       // Show the last 100 published posts.
       $query = array('post_per_page' => 100,
                      'post_status' => 'publish' ) ;

       // run the query
       $loop = new WP_Query($query);

       // start the output buffer to save contents of loop
       ob_start();

            // do normal loop stuff
            if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post();

                // show content or whatever you like
                ?><h1><?php the_title() ?></h1><?php
                the_content();

            endwhile;endif;

            // save the output buffer contents in a variable
            $loop_output = ob_get_contents();

       // clean the buffer as we will be using the variable from now on
       ob_end_clean();

       // transient set to last for 1 hour
       set_transient('loopOutput', $loop_output, 60*60);
}

// output the new created loop if loop content does not exist. 
echo $loop_output;

?>

Rounding up

Using the transients API can significantly increase the speed of your WordPress plugin, theme or widget. It really is worth considering making this standard practice when creating for WordPress in future.

Update

Thanks loads to Erik for pointing out that you have to have WP_CACHE enabled for any of this to work. As the ChiefAlchemist rightly says, that would cause many a grey hair and long night not to know.

To set WP_CACHE, you need to edit the wp-config.php in the root of your webserver (or one directory above if you are security minded).

define('WP_CACHE', true);
/* Absolute path to the WordPress directory. */

It goes at the end just above the line “Absolute path to the WordPress directory”

Caching Shortcodes

Also by request, shortcodes. The only issue with caching shortcodes is that you need to consider where and how it will appear. here are a few different examples of where you might find yourself using shortcodes.

  • Shortcode without any settings, but relates to the post. i.e. share links to social networks.
  • Shortcode with settings. i.e. show a gallery by ID.
  • Shortcode with no settings or relationships. i.e. show current number of facebook followers.
  • A mix of all of the above.
// shortcode without any settings but relates to the post.  can only be used inside the loop.
// shortcode usage
// [share] 
function sharelinks( $atts ){

$links = get_transient('share_links' . get_the_ID() );
if($links === false){

// add the links you want
$links = "<a href='https://www.facebook.com/sharer.php?u=" . urlencode( get_permalink() ) . "&t=" . get_the_title(). "'></a>";

// save the count for 30 days
set_transient('share_links'  . get_the_ID() , $links, 60*60*24*30 );
}
// return the response. **do not echo**
return $links;
}
// set shortcode 
add_shortcode( 'share', 'sharelinks' );

Shortcode example with settings

// shortcode usage
// [my_gallery id="1" height="300" width="200"] 

function shortcode_gallery( $atts ){
// get the values from inside the shortcode and make them variables
// the id, height and width have the default settings inside the array if not set
// in the shortcode. 
extract( shortcode_atts( array(
    'id' => '1',
    'height' => '100',
                'width' => '60',
  ), $atts ) );

$gallery = get_transient('gallery' . $id . $height . $width );
if($gallery === false){
//
//  Do the code that creates your gallery and return the output to a variable called Gallery
$gallery = get_my_gallery($id, $height, $width);

// save the count for 30 days
set_transient('gallery' . $id . $height . $width, $gallery, 60*60*24*30 );
}
// return the response. **do not echo**
return $gallery;
}
add_shortcode( 'my_gallery', 'shortcode_gallery' );

Shortcode to show Facebook follow count

 
// shortcode usage
// [fans]
function facebook_fans( $atts ){
$fans = get_transient('facebook_fans');
if($fans === false){
// put in your own facebook ID
$page_id = "YOUR PAGE-ID";
// get the XML from facebook with the response
$xml = @simplexml_load_file("https://api.facebook.com/restserver.php?  method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
// get the fan count
$fans = $xml->page->fan_count;
// save the count for 1 day
set_transient( 'facebook_fans', $fans, 60*60*24 );
}
// return the response. **do not echo**
return $fans;
}
// set shortcode 
add_shortcode( 'fans', 'facebook_fans' );

The only trick to making this work really is having a variable that you can add to a word stem. As with the share links I used the post id to set it seperate, with the gallery I used the id, height and width as this will give full caching no matter how many different ways the shortcode is used.

More from the Website Speed series

The post Website Speed Part 3 – Caching WordPress appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/website-speed-part-3-caching-wordpress/feed/ 21
Website Speed Part 2: Working With and Optimizing Images for the Web https://speckyboy.com/website-speed-part-2-working-with-images/ https://speckyboy.com/website-speed-part-2-working-with-images/#comments Wed, 30 Mar 2011 08:30:14 +0000 http://speckyboy.com/?p=11901 This is the second part the website speed series where we closely look at the techniques employed to make a website run as fast as possible while still maintaining it’s...

The post Website Speed Part 2: Working With and Optimizing Images for the Web appeared first on Speckyboy Design Magazine.

]]>
This is the second part the website speed series where we closely look at the techniques employed to make a website run as fast as possible while still maintaining it’s stunning look and feel.

Images can make or break a website, whether that be adding a humanist feel to a site, adding animation and mouse over effects or finalizing that amazing design that just can’t be achieved with CSS alone. Yet all these images could cost the biggest price of any website, loss of visiting traffic. If a website takes too long to load or is unusable due to all of the images then it’s game over as the user will quickly go back to Google and search again.

There are however many techniques that you as a web designer can use to either reduce the number of images that are loaded or reduce the size of those images.

Before we get started, I’m not going to look at SWF as it does not work on the iPhone/iPod/iPad at this time or WebP as it is currently super-limited in browser support, or Silverlight as it needs an extra plugin installed….

So without further a-due, on with the list of techniques…

#1: Choose the right image type for the job

There are currently quite a few image formats that are used within web design: PNG8, PNG24, PNG32, JPG and GIF. These are widespread and supported by every browser, all are very different and are all suited for a particular use. Lets take a closer look at each.

GIF ~ *.gif

  • Where to use: IE6 clients when you need transparencies, non-complex images with less than 256 colors and it can be animated.
  • Limitations: Can only hold up to 256 colors in total.
  • Pros: Their transparencies work on all browsers, the smallest size completely blank image (see CSS sprites further on), very easy to reduce the color depth to make smaller a file size and offers an animated format.
  • Cons: Images often loose quality when in GIF format as the image creation package has to workout the closest color match. Not very good for photo’s. Animations can be massive in size if you are not careful. Images can appear jagged, and transparencies can sometimes have bleed on the edges.

JPG ~ *.jpg or *.jpeg

  • Where to use: Perfect for photos or images where no transparency is needed, such as background gradients.
  • Limitations: No transparencies, not very good with text.
  • Pros: Excellent for photos, 24-bit color giving 16 million colors.
  • Cons: JPGs are much larger when creating files with few colors in it, they have lots of extra info included in the file (Exif) such as camera, ISO and shutter speed, which are not needed on the web. No animation support.

PNG8 ~ *.png

  • Where to use: Any browser with the exception of IE6 when needing transparencies.
  • Limitations: Like GIF only has a maximum of 256 colors.
  • Pros: Similar file size to GIF but with a sharper output. Transparencies work great. Excellent for CSS sprites when using only up to 256 colors and reduced color depth images.
  • Cons: Not so handy with IE6 as you would need a separate PNG fix to make transparencies work, but that only applies to images with transparencies. Not very good for creating photo quality output. No animation support.

PNG24 ~ *.png

  • Where to use: High quality images that do not require a transparencies.
  • Limitations: No transparency support.
  • Pros: 24 bit colors giving 16 million colors for very high quality images.
  • Cons: No transparencies and often larger than JPG when used for photos.

PNG32 ~ *.png

  • Where to use: High quality images, icons and colored based opacities.
  • Limitation: None really when it comes to the web.
  • Pros: 24-bit color and 8-bits to handle transparencies. Excellent for icons, gradients and other images. Easy to crush.
  • Cons: Over sized KB’s when creating photo images.

Rule of thumb

So to round that up into a rule of thumb, use JPG for photo’s and gradients without transparencies, use GIF for IE6 transparencies, use PNG8 for all other browsers with low color depth images and transparencies and use PNG32 for the best quality and transparencies.

Of course you can use PNG with transparencies on IE6, but it will need the addition of a .htc file and possibly a Javascript file to make it work in all situations, or just a Javascript file depending on what version of the PNG fix that you use on your site to make it work, it will however slow down loading time.

#2: Use the right tools to create a web friendly image

Many designers and design studios use Photoshop and Illustrator to create their images, whether that be logos, gradients, icons or whatever. But these tools may be a great for creation, they are at times truly woeful for outputting images for the web.

Often images that come out of Photoshop are up to 50% larger in KB’s than are actually needed for the quality, and Illustrator is often not much better when talking about Jpgs. On top of that they don’t support Gif animations that some of your clients may desire. So instead of using the save for web options that come with Photoshop, just save it as a PSD and open it in Fireworks (or maybe Illustrator depending on the output medium) and export for the web from there.

Fireworks is the superior Adobe product for creating web ready images. OK, I am a mega bias Fireworks fan, so to prove the point to myself I’ve done a bunch of tests and have the results below. For me the most consistent performer is still Fireworks, especially when you look at Jpg, Illustrator is a far superior tool over Photoshop, with Photoshop being truly dire on nearly all file formats.

Photoshop Illustrator Fireworks
1x1px transparent Gif 1,101bytes 43bytes 43bytes
Sample Jpeg image(my cat Jack), orignal size 2848×2134 reduced to 800×599. Output at 80% quality 124,206bytes pre-crushing


119,393bytes post-crushing

119,599bytes pre-crushing


114,844bytes post-crushing

51,838bytes pre-crushing


51,838bytes post-crushing

PNG8 output with transparencies with facebook icon 3,456bytes pre-crushing


2,582 bytes post-crushing

1,805bytes pre-crushing


1,738 bytes post-crushing

1,762bytes pre-crushing


1,646bytes post-crushing

PNG32 output with transparencies with Facebook icon 3,654bytes pre-crushing


2,798bytes post-crushing

2,831bytes pre-crushing


2,760 bytes post-crushing

2,882bytes pre-crushing


2,802bytes post-crushing

Animated Gif Yep can do Not Possible Works perfectly

Do feel free to complain that I did not use Gimp or any other software for this comparison, and if you wish do provide me with the results I will certainly add it to this table. All versions of the Adobe software were from the CS5 set, lets hope that CS6 will be even better.

#3: Learn how to output the lowest kb’s with highest quality

Firstly, it’s got to be said that there are no hard and fast rules for choosing the image that will give you the best output quality while still maintaining the lowest kb’s. It’s all about trial and error.

Ok, these are the rules of thumb mentioned before, that for example if your working with images that are above 256 colors forget about Gif and Png8, and for most photo’s Jpg’s are the best, for icons with transparencies Png32 will always kick butt, but for gradients without transparency then it will usually be Jpgs, for transparency it will be Png32, borders and lines tend to have transparent backgrounds so Gif, Png8 and Png32 are usually the best.

Lets take a closer look as some examples of where a wrong choice in the image format can cost 100’s of KB’s of size and maybe valuable seconds of loading time. Again, I am using Fireworks as the tool for creating all of these images due to it’s consistent results and then ImageOptim for crushing.

A text image with a low number of colors

This really simple (very un-artistically made) image is pretty damn ugly, but will give you a good idea of what I am trying to illustrate. It’s the kind of thing that is often used on a website to create a meaningful feel with text only.

Ugly text image

GIF Jpeg png8 png24 png32
Size in bytes after crushing 4,210 bytes 9,718 byte 2,554 bytes 2,385 bytes 2,827 bytes

As you can see, PNG24 wins out on this image (after crushing, PNG8 before crushing), with PNG8 coming a close second, at the other end of the scale JPG performs incredibly badly, not only in KB image size but also in picture quality. You can view a comparison page yourself to take a look at the output.

A photo image

Another take of that photo of Jack, this time re-sized to 400px wide and formatted into various different file types.

GIF Jpeg png8 png24 png32
Size in bytes after crushing 36,415 bytes 100% = 134,915 bytes
80% = 20,368 bytes
80% Smoothing 2 = 19,479 bytes
80% Smoothing 2 Sharpening off = 14,912 bytes
29,904 bytes 178,727 bytes 179,044 bytes

This time Jpg is the clear winner and when turning off the sharpening and setting the smoothing to 2, without any perceivable change to the image I was able to knock off many of those extra kb’s. Again I have made a comparison page so that you can check the output.

Here is a screen shot of the Export Wizard of Fireworks that shows the settings I used to get the lowest size image possible.
(Click the image to see it properly).

An icon

Icons are very important in modern web design, and their quality is exceptionally important. Just one bad looking RSS icon can make a whole site look really bad. The thing that you have to think about when creating icons is what type of background it will be used with. If you don’t know what color or colors it will be then GIF, PNG8 and PNG32 are your only options, which means that you have to consider how many colors you need to have in it’s creation also. If you want to have over 256 colors then PNG32 is your only choice. Here is a Facebook icon as PNG32 on the left and PNG8 on the right. If you look carefully you will see the quality difference with the PNG8 version obviously having banding.

Some Icons in a sprite

It really depends on if you are planning to have many colors or not. If, for example, you are making a set of icons that are only white are going on a black background, then it’s perfect to use PNG8, but if you are planning to have the iPhone icon style using many colors in the same sprite set with a background transparency, then PNG32 is the only way.

This is the 32px sprite set used for the share and follow plugin, click the image to see it in it’s full size.

A gradient for a background

If there is no transparency involved then go for Jpeg every time, it’s perfect. But if you need to have a transparency then go for PNG32 which will allow for the most amount of color changes, as PNG8 only can do 256 colors. Most of the time you will also want to reduce your gradient to only 1px wide so that it does not take up load time and then use repeat-x to repeat the gradient across the whole of the body of the HTML document. See point #9 on this list for examples.

Some borders and lines

Same rules for borders and lines as the gradients above. If there is no transparency involved then go for Jpeg first every time, it’s nearly always perfect. But if you need to have a transparency then go for PNG32 (or PNG8 if you don’t need many colors). There will be more about gradients, borders and lines on point #9.

#4: Crush those images before use

Most images come with extra ‘fluff’ inside the file. Take Jpeg for example that has all of the details of what camera, shutter speed, ISO, focal length, what camera was used…etc. All within the file in Exif format. All of this is not needed and will just add extra bytes to file size. To some extent, this is the same with all file formats and because of this there have been many different apps developed for stripping the ‘fluff’ out of images.

Off-line tools

MAC: ImageOptim is probably the best tool to use on a MAC as it deals with Gif, Jpeg and PNG. What it does is that it packages 5 different tools in one handy GUI to explore your images and make them as small as possible.

PC: pngcrush is handy if you like the command line and you work with a lot of Png’s.

There are also a mountain of Jpegtran apps for image crushing, or manipulation for both Mac and PC.

On-line tools

Smush.it is a Yahoo project that allows you to either upload directly or via a URL. It offers, if possible, lighter images to replace the ones you have uploaded or have on an existing page.

Punypng will try to reduce the size of any image file that is uploaded. It works with PNG, Gif and Jpegs.

If you happen to use any offline or online tools not listed here that you find excellent, please do comment so that they can be shared.

#5: Use CSS Sprites for images

CSS sprites are one of the key tools for speeding up websites and are really simple to get your head around if you have not used them before. In simple terms a CSS sprite is an image that contains many different images on it. They could be logos, buttons, menu items…anything you like. Sprite images can be used for mouse over effects, standard link buttons, or maybe even backgrounds for input styling.

Why CSS sprites are so, so important is that they basically cut down on the number of connections made to the server. No matter how small your images are in KB’s, if there are many of them then it will take a long time to download them as the browser can only download a limited amount at once. Using CSS sprites downloads one image that will be used many times, thus 1 connection, leaving the browser free to download other content.

Here are 3 different ways to show CSS sprites on screen (see here for the demo).

I) Image replacement, using display:none to hide the text

<h1 id="logo"><a href="#"><span>Logo words</span></a></h1>
#logo a {
background: transparent url(sprite.png) no-repeat -111px 0;
height:60px; 
width:120px;
display:block}
#logo span {display:none;}

This technique was very popular about 5 years ago. Some designers still use it as it keeps the text visible for Google to find inside the first H1 of the site.

On the downside it means that the logo will not be picked up by Facebook when sharing your site, so you have to add some head code so that Facebook will pick up your preferred image.

II) Using text-indent and overflow together

<ul>
<li><a href="#" class="facebook">Share on Facebook</a></li>
<li><a href="#"  class="twitter">Share on Twitter</a></li>
</ul>
.facebook {
background: transparent url(sprite.png) no-repeat 0 0; 
height:24px;
width:24px; 
text-indent:26px; 
overflow:hidden;
display:block
}
.twitter {
background: transparent url(sprite.png) no-repeat -25px 0; 
height:24px;
width:24px; 
text-indent:26px; 
overflow:hidden;
display:block
}

Again, this keeps the original text for Google to find in the HTML markup, and saves on the display:none. So, less code to make this happen. What we do this time is tell the text to appear outside the block area of the A tag, where we have set the overflow text and the stuff outside the block space, to not show up at all.

III) Using the IMG tag with a blank image

<a href="#" >
<img src='blank.gif' alt='descriptive words for google' 
   height='60' width=60 class='foursquare' />
</a>
.foursquare {
background: transparent url(sprite.png) no-repeat -50px 0;
}

Sprites can also be written using an inline style, here is the IMG tag version using an inline style.

<a href="#" >
<img src='blank.gif' alt='descriptive words for google' 
style='background: transparent url(sprite.png) no-repeat -50px 0;' 
height='60' width='60' />
</a>

Thus you can save on the CSS, which is handy when your are dealing with many sprites with many images on each. For example, with my plugin Share and Follow I use this style as I have around 70 icons per set and 5 sets in different sizes, giving 350 extra CSS statements all needing some unique CSS. And that is not mentioning the 26 different icon sets that the plugin offers. This would add up to a huge total of 9100 extra CSS statements to be placed in the CSS file. That would not be good, would it?
So, on this occasion rather than adding 9100 extra CSS statements in the external CSS file, I choose to add some extra in-line styles directly into the HTML.

The important thing to notice about this method is the use of the blank.gif which stretches to meet the size of the IMG while the CSS background image comes from the sprite. So in theory there are 2 images loaded to make this happen.

Here is the sprite file used for the above examples:

It was built using Project Fondu’s Sprite Generator. A couple of things to remember when building sprites is that you should always build them horizontally, as it is often faster (according to Yahoo testing), and also always keep the space between icons as small as possible.

Here is a set of examples with our sprite file from the Fondu Sprite Generator against hand-made sprites:

Size in bytes Size after crushing
fondu horizontal
14,797 bytes 8738 bytes
fondu vertical
14,940 bytes 8706 bytes
horizontal hand built png8
3,227 bytes 3,012 bytes
horizontal hand built png32
9,791 bytes 8,856 bytes
vertical hand built png8
3,188 bytes 2,972 bytes
vertical hand built png32
9,818 bytes 8,705 bytes

You will notice that Project Fondu’s Sprite Generator does not do the best job possible as the 24px icons could be more efficiently packed on the horizontal version. This is because I am using different sized icons in the same set. If they were all the same height and width, it would have made a much better output.

In other words if you are a total speed nut, do consider hand building and trying both vertical and horizontal arrangements, but be aware that you will need to work out all your own CSS.

You will also notice that the Png8 version on this occasion is more than adequate. Had there been more sprites with more colors used then this would have not been the case.

#6: Get to grips with background-image, background-repeat and background-position

When making sprites it’s easy to get carried away with making very long CSS statements for every image, where each line looks something like this:

.item1 {
background:transparent url(sprite.png) no-repeat 0 0;
height:24px; 
width:24px; 
}
.item2 {
background:transparent url(sprite.png) no-repeat 0 25px;
height:24px; 
width:24px; 
}
.item3 {
background:transparent url(sprite.png) no-repeat 0 50px;
height:24px; 
width:24px; 
}

where it would be much more efficient to write:

.item1, .item2, .item3 {
background-image:url(sprite.png);
background-repeat:no-repeat; 
height:24px; width:24px;
}
.item1{background-position:0 0}
.item2 {background-position:0 25px}
.item3 {background-position:0 50px}

Or, if you are lucky enough to have all of the sprites that you want to display inside the same list and are using the IMG tag:

li.sprite img {
background-image:url(sprite.png);
background-repeat:no-repeat;
}
.item1{background-position:0 0}
.item2 {background-position:0 25px}
.item3 {background-position:0 50px}

#7: Does it have to be an image, or will CSS do the job?

Ok, this does go against the nature of this entire article, but do check if you can do the same thing you are trying to achieve with images in CSS alone. For example, can you get that background color you want just with a DIV and the correct CSS? If you can, it will be less bytes and less files used.

Do remember that gradients created with CSS alone are going to slow down your total pages loading time.

#8: Using DATA URI images

It’s become a bit of a fad recently to input images directly in as data elements inside either in-line style code, src URI’s or CSS. For those that don’t know what the Data URI images are, they are BASE64 encoded images just like images that are saved in a database, but directly entered into either HTML or CSS.

They can be used to reduce the number of connections needed to dowload images and are highly recommended for people who are developing exclusively for mobile devices. But for us mere mortals that have to cross browser develop, it’s worth steering clear of them as they do not work on anything below IE7, and can only be up to 32k in IE8. They can also be a 1/3 bigger than using a single image to do the same task, brought back to maybe 2 or 3% with gzip. The advantage is that they use less connections and thus faster loading times.

However if your still interested in them check out this Wikipedia page.

By my mind, it’s only mobile developers that would want to think about this. So, maybe you want to investigate this for CSS inclusion in a mobile theme where you want to have some images.

#9: Double up, treble and more; more on the art of background positioning, size and repeats.

CSS sprites are not limited only to items that are icons and menus, they can also be applied to lines, borders, shadows and background gradients. All it takes is a bit of layering know-how and you can re-use the same image many times. The only thing that you have to consider when building your sprites this time is if they will be used to display things on either a horizontal or vertical line.

When building a vertical orienteteted sprite to display items that will be repeated on a horizontal line, the major things you will want to be putting in there will be the background gradient, any horizontal line styles and finally any drop shadow effects.

Take this html for example

<div class='gradient'></div>
<div id='wrapper'>
   <div class='box'> 
    <h1>Andy Killen</h1>
    <hr class='top-line' />
    <h2>Speed demon of the internet</h2>
    <hr class='alert'/>
    <p >Available for consultancy, talks, training or performing site speedup's</p>
    <ul>
        <li>telephone: +31 653678603</li>
        <li>email: <a href="mailto:andy@phat-reaction.com">andy@phat-reaction.com</a></li>
        <li>website: <a href="https://phat-reaction.com">phat-reaction.com</a></li>
        </ul>
    </div>
<hr class='shadow'/>
</div>
<div class='reverse-gradient'></div>

…and the CSS:

h2,hr,html,body {
margin:0;
padding:0;
position:relative;
border:0
}
.gradient,hr,.reverse-gradient {
background-image:url(horizontal-repeats.png);
background-repeat:repeat-x;
}
.gradient {
background-position: 0 0;
position:fixed;
height:100px;
width:100%;
top:0;
z-index:-1
}
#wrapper {
margin:0 auto;
padding: 30px 0;
width:400px;
z-index:3
}
.top-line {
background-position: 0 -100px;
height:10px
}
.alert {
background-position:0 -110px;
height:10px
}
.box {
border:solid 1px #ccc;
margin:0; 
padding:10px 20px 0;
background-color:white;
}
.shadow {
background-position:0 -120px ;
height:25px; 
}
.reverse-gradient {
background-position:0 -145px;
height:100px;
position:fixed;
bottom:0; 
width:100%;
z-index:-1
}
ul {list-style-type:none}
a{color:#999}
a:hover{color:#000}

(Lots of carriage returns added for readability)

With the original here, or the image that makes all the gradients and lines here.

As you can see that with a handful of code and one image of 1.2k in size (without being crushed), it is possible to have many gradients, shades and line styles all inside the single file. This will as ever speed up loading time as there is only one request per file and not five in this case.

And of course this does not have to be limited to things that are displayed on the horizontal, it can also be used to build up vertical elements also.

#10: Don’t forget about the Favicon!

The favicon is often forgotten about, but it is something that loads with every page. On most sites if it is missing but still linked then the 404 error page that will show will cause even more traffic than an efficient image, especially when you consider the trend of having very comedic 404’s with stunning imagery.

When creating the favicon try to reduce the number of colors that you use to a minimum and try not to have a final file size much above 1K.

Although it might be tempting and fun, try to resist the temptation to create animated Gif favicons if you want to keep a sites speed down. They look great and can add to your branding but they don’t work on IE and come with a cost in size.

Possibly the best tool for reducing the size of an existing favicon is ImageMagick (MAC, PC and UNIX). Using the convert function from the command line you can reduce the colors until you find the perfect balance.

Here is an example of the command line code you would have to enter to get it to work

convert -colors 4 favicon.ico new-favicon.ico

What this command does is run the convert command with the option to adjust the colors, and then reduce the number of colors to 4, it then says take the original favicon.ico and then outputs the new version with 4 colors as new-favicon.ico.

convert -colors 16 favicon.ico new-favicon.ico

This command would make it 16 colors. Try you favicon out with 2, 4, 8, 16 and 32 colors, and choose the one that makes your favicon look good while having the fewest number of colors.

#11: Remember the 25K rule for mobile clients

If for any reason you are working with any mobile device in mind, remember that the iPad can only handle caching of images that are 25K (281K cache total) and lower. The iPhone 3G is 51KB (1.05MB total cache) and its 102KB (1.9MB total) for the iPhone 4. So if you are building massive sprites you might want to think again and have it split up in to 2 or three seperate sprite sets.

Read more about mobile device caching here.

#12: Don’t scale down images, use the right size (or even scale up)

I am sure that every designer/developer knows this already, but here goes…. Don’t take a large image and fit it in a small space. So don’t make a 1024 x 768 image fit into a space of 800 x 600. Use an image of the right size in the first place. It’s just wasting you KB’s on the download speed.

Conversely if you want to take a smaller image and make it fit into a larger space then it will load just fine and make the page load time very quick. For example I use this technique to make a 640 x 400 image scale up to be the body background image size. Of course it gets a little blocky on larger screens but as it’s a background rather than a foreground, nobody minds.

#13: Don’t forget to set the height, width and alt

Setting the height and width helps the browser to know how big things will be before the image has been downloaded so that the page can be drawn and presented to the user quicker. Setting the Alt text makes the image accessible, validates your HTML and helps Google Image Search.

img src='image.jpg' width='30' height='40' alt='image description for a blind person'/

#14: Setup the expire date, and ETag on the server

Setting up the expiry date on images can help by telling the browser that the images are not going to change for a period of time. This can be any period that you like, but be aware that if you want to change the sprite or image you will also need to change it’s name to force pre-cached browsers to load a new file and not load the old version.

It’s worth configuring ETags also as they help with caching, what they do is help the server to reply with just a small header confirming that the image or files have not changed. Each ETag is unique per file so the server can keep control of what changes and what has not when the client browser requests it.

For more information about expire headers and etags, you’ll need to wait for the ‘Configuring Servers for Speed’ part of this Website Speed series.

#15: Use a CDN

As ever a proper CDN will do many things for you. Firstly it will reduce the load on your server allowing for more browsers to connect at once, and secondly it offers a more local version of an image because it will pull them from a server that is closer to the user. It will also not transfer cookie info. All of this making page loads quicker all round.
See Part 1 of this series for a list of CDN providers and for a larger overview.

#16: No cash for a CDN? Invest $10 on a new domain for serving Static Content

By simply having a 2nd domain name that also points at your web server you will be able to serve more images in a parallel download while it brings down the other content from the main address.

It’s much better as it does not transfer cookie info, and it offers twice as many connections at once to the server. The browser should be able to make only 2 connections per DNS address, so having 2 different DNS addresses doubles the amount of traffic. Most modern browsers can make 6 or more connections at once so doubling up will allow for 12 things that can be downloaded simultaneously.

Do remember to use a completely different domain name rather than a sub-domain of the one you are using for your main server as you will be wasting a lot of your effort. For example Yahoo! uses yimg.com, YouTube uses ytimg.com, Facebook uses static.ak.fbcdn.net and so on.

#17: Make faster animated GIF’s

Last on the list are animated GIF’s as its not made by most designers, so it’s more of a footnote than a main item. There are a few things to remember when creating animated GIF’s when you want them to be low in KB’s….

  • Use the same background in every frame of your animation.
  • Use the same colors in the whole of the animation.
  • Don’t use too many frames.

The whole idea here is to reduce the number of colors so that the GIF can be as small as possible, so if you are using animated GIF’s to represent Ajax actions, then use only 4 frames and not 16. If you are making an advert keep your creative juices to a color minimum. Of course none of this matters if you’re placing your advert on someone else’s site and you just don’t care ;D

Rounding up

That’s the end of part 2 of the Website Speed series, there’s much more to come but understanding these 17 points will make a massive difference to your website speed. If you take nothing else from this, the main thing you should consider is crushing your images, and to use CSS Sprites! Oh, and don’t make your web images in Photoshop.

Of course yet again, if you need more personal help with one of your websites to make it incredibly fast don’t be scared to contact me as I will gladly train your team on the best techniques or make the changes to your site to make it in the top 5% of all websites out there.

The post Website Speed Part 2: Working With and Optimizing Images for the Web appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/website-speed-part-2-working-with-images/feed/ 12
How to Write More Efficient CSS to Speed up Your Site https://speckyboy.com/website-speed-part-1-write-more-efficient-css/ https://speckyboy.com/website-speed-part-1-write-more-efficient-css/#comments Tue, 08 Mar 2011 23:46:52 +0000 http://speckyboy.com/?p=11643 As part of my new position as CTO of Speckyboy, I’ve decided to write a series of articles that will help you understand what it takes to make a truly...

The post How to Write More Efficient CSS to Speed up Your Site appeared first on Speckyboy Design Magazine.

]]>
As part of my new position as CTO of Speckyboy, I’ve decided to write a series of articles that will help you understand what it takes to make a truly fast site. As you may have noticed Speckyboy just got a shot in the arm recently and is running a heck of a lot faster.

This is because of all of the tips that I will be listing in the “Website Speed” series, where the focus is 100% on load times.

Why should you care about your CSS? Why when products from Adobe and others output entire websites with HTML and CSS, all pre-made and ready to deliver to the customer?

The reasons are simple, all of those ‘pop-out’ builder apps will add lots of unnecessary CSS and HTML in lazy ways. Slow websites suffer from high bounce rates and lower search engine rankings.

In surfing terms, ‘pop-outs’ are created on a production line and used by beginners that surf for a day, while a custom board is handcrafted and used by a pro. People use pop-outs as they are heavier, go slower and offer the beginner a more stable platform to work on. Whereas a custom board is lighter and tailored exactly for the rider so that they can perform to the top of their ability. The same it true when you develop web pages.

You can, of course, use pop-out website creators to make your websites, but you will be showing the rest of the web producing world how much of a novice you really are, as your website will be slow to load and heavy on kb and have lots of extra HTML and CSS to make it work.

#1: Write your own Custom CSS and HTML

Custom CSS and HTML will always make your site fast. Always try to reduce the amount of DOM elements you use, or in other words if you don’t need to have a HTML tag there get rid of it.

Here is a good example of where a List is used where it does not need to be, in the footer of a website


<div class="example-footer-1">
<ul>
 <li>&copy; <a href="#"> my website 2011</a></li>
 <li><a href="#">privacy statment</a></li>
 <li><a href="#">sitemap</a></li>
 <li>site created by <a href="#">my amazing company</a></li>
</ul>
</div>

235 characters of HTML


.example-footer-1 {
  padding:20px;
  border-top:solid 1px #cccccc;
  border-bottom:solid 1px #cccccc
}
.example-footer-1 ul {
  list-style-type:none;
  padding:0;
  margin:0}
.example-footer-1 ul li {margin-right:3px; display:inline}

215 characters of CSS

where as


<div class="example-footer-2">
<p>
 &copy; <a href="#"> my website 2011</a>
<a href="#">privacy statment</a>
<a href="#">sitemap</a>
site created by <a href="#">my amazing company</a>
</p>
</div>

197 characters of HTML


.example-footer-2 {
  padding:20px;
  border:solid 1px #ccc;
  border-width:1px 0
}
.example-footer-2 p {padding:0;margin:0}
.example-footer-2 a {margin:0 3px 0 0}

153 characters of CSS

Click here to see the two different examples in a single demo file.

The things that were different in example 2 were

1) set the border width for all borders then unset the border width for the sides rather than exclusively setting the border for both top and bottom.

2) reduced the border width color by 3 characters using the shorter form of #ccc rather than #cccccc.

3) did not use a list as this really is not a list of things. Just used A tag only in the HTML. It is common practice for many designers and pop-out makers to use a list here.

4) changed the list for a paragraph tag to keep HTML validation correct, which reduced the links by 9 characters per list element. ‘<li>’ and ‘</li>’ are not needed any more, and changing ‘<ul>’ and ‘<p>’ saved a character top and bottom.

5) changed the margin statement from margin-right:3px to margin:0 3px 0 0, although it does not save any space on this statement if your using more than one margin statement at once it will.

#2: Get rid of un-needed spaces, tabs and carriage returns

If you check with the W3C, WordPress or others they recommend that you write your CSS in a top to bottom style, for example, the official way to write CSS needs carriage returns, tabs, and spaces to aid reliability.


.example  {
  padding : 20px;
  border : 1px solid #ccc;
  border-width : 1px 0px;
}

Character count 90, 4 carriage returns and 3 tabs
If you want a faster site you should minify that as much as possible when you code it:


.example{padding:20px;border:solid 1px #ccc;border-width:1px 0;}

Character count 64, no carriage returns, no extra spaces, no extra characters and no tabs.

What happened here was simple, the extra fluff was removed. It will still validate quite happily but will not take up as much space.

To save yourself a bunch of time doing this by hand you could use a text editor or IDE to do most of it for you. Here are a hand full of find and replace statements you can run.

  • replace ” {” with “{“
  • replace ” }” with “}” [1]
  • replace “: ” with “:” [1]
  • replace ” :” with “:”
  • replace “; ” with “;” [1]
  • replace ” ;” with “;” [1]
  • replace “, ” with “,”
  • replace ” 0px” with ” 0″
  • replace ” 0em” with ” 0″

[1] it is worth running these commands 2 or 3 times in a row to get rid of all those un-needed spaces.

Remember : CSS minification tools will never be as efficient as you can get by hand. Take W3 Total Cache’s minification, for example, it does not remove the spaces before/after a colon, before the opening curly brackets, or after a comma. What W3 total cache does well is remove carriage returns that help to make your file readable at all.

#3: Get rid of un-needed semi-colons at the end of each CSS statement

Taking our efficient no spaces, tabs or carriage returns CSS statement we can make it 1 character shorter by removing the last semi-colon from the end of the statement


.example{padding:20px;border:solid 1px #ccc;border-width:1px 0;}

… becomes …


.example{padding:20px;border:solid 1px #ccc;border-width:1px 0}

So our 64 characters long statement becomes 63 characters long.

If you consider that there are often upwards of 200 CSS statements in a CSS file, this saves 1 character per statement, so for example with a 200 statement file 200bytes are removed. Easily removed if you look for “;}” and replace with “}”

#4: Learn CSS Properly

You might think I am teaching you to suck eggs with this statement, but please stay with me on this one. I often see from other people’s designs and code that they do not understand how CSS works properly. They have most likely worked things out by reading websites here and there, and not necessarily knowing the truth of a situation. After all there is a lot of the blind leading the blind out there on the Internet. So cut out the bullshit and get yourself some proper understanding of CSS. For example on nearly every website I have re-coded for a corporate I have seen:


li {list-style-type:none}

where it should not be applied to the List Element but the list as a whole, like this


ul {list-style-type:none}

Or take these examples of either wasted space or silly code


#header {width:auto; margin: 0 auto;}
#footer {margin: 0 0px 0 0px; padding:0 0 0px 0}
#sidebar {
background-image: url(images/image.png);
background-position: center top;
background-color:transparent;
background-repeat: no-repeat
 }

Where #header must have a specific width applied for the auto margin to center it, so 2 bits of wasted code only leaving the margin-bottom and top of 0 to be active.

The #footer could have just been margin:0;padding:0;

#sidebar could have just had background:transparent url(images/image.png) no-repeat center top;

There are usually many more on every site that I have made quick, be that for a major corporate or for a small design company. This usually stems from two places, a designer who does not really code, or a back-end coder who does not really know CSS.

Do yourself a favour and get some books on the subject, don’t rely on websites to give you the answers here. Personally, I find the Sitepoint books the most readable. Oh, and do try very hard to understand the difference between browsers and their CSS level so that you can gracefully degrade your code when still having to support IE6 for corporates.

#5: Watch out for Wasteful CSS Resets

Many people use a CSS reset at the start of their CSS code to try to get a level playing field across all browsers. While I find this a good idea, the execution is often misguided.


html, body, div, span, object, iframe,
h1, h2, h2, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent; }

This could not be more wasteful in many places. Lets take it apart for a second.

footer, nav, section, label, dfn, cite, kbrd, code, samp, b, i, strong, em, canvas, tr, thead, tfoot, tbody, span, var & div do not need to be in this list at all as they are already pre-defined by all browsers as no padding, no margin, no background, no borders, no outline, don’t have an applied font size. Wasted space.

sup, small & sub should not have font-size of 100% applied to them as they should be a different size than the rest of the text fo making it 100% kills the point of it. Again wasted space.

sup and sub are not supposed to have a vertical align of baseline, sup makes it small and above the line, sub makes it small and below the line.

I’ll argue that th and td should have vertical-align:top as that is almost always the way that they are used and that they actually need to text-align:left to make them consistent as on some browsers th is in the middle and some it is on the left.

So lots of wasted space and also lots of extra applied items that the browser has to think about before processing the entire page. Because these rules come first in the page they will be applied to all items on the page and then later CSS will overwrite it. Basically this slows down everything and makes your CSS file bigger than it needs to be. A waste of time all round, don’t be fooled into thinking that the ‘cream of the web’ know what they are doing, they just cut and paste also.

#6: gzip your CSS

Gzip is much like normal zip that you use almost everyday. It is a tool used to compress files down to their smallest size so that when they are sent to the browser they use less network bandwidth.

If your server allows it, be that apache, tomcat, lighttp or IIS, always gzip your CSS. Be aware that many hosting companies will turn off gzip for their servers as it takes additional processing power to make it that way and they do not want their servers to have any lag. Also be aware that if you are an exceptionally popular site the extra processing to gzip your content can be detrimental to your server performance, you may have to invest in extra processing power.

There are different levels of gzip’ing, on the whole most people use ‘-9’ or ‘level 9’ gzip’ing as it is the one that makes the files the smallest, but also takes the most processing power.

Greater details and full instructions for this will be coming soon in the “Configuring Servers for Speed” part of this series.

Remember : Not all browsers can handle gzip’ing and some browser security tools stop it’s usage, so focus on having a small CSS file in the first place.

#7: Put Stylesheets at the Top of the Head

Always, always, always put the stylesheet at the top of the HEAD section of your HTML, just below the title. This is because it wants to be downloaded as quickly as possible so that it can be applied to the page. Do not for any reason put a STYLE tag inside the body of your html unless it is 100% necessary for that specific task, add it to your external style sheet.

#8: Always use an External Stylesheet

External style sheets are good as they can be gziped and cached on the browser, if you put the style inline in the head it will be loaded freshly each time the page is loaded, making the response time slower.

#9: Don’t use CSS expressions

CSS expressions are poorly supported, and take additional processing power. If you want to, for example, have a different background color based on the time of day, do it at the server end by generating your CSS dynamically, or write some funky Javascript that does the same task after all of the files have loaded for the page.

#10: Don’t use @import use link

Some people use @import to include CSS into their HTML, this is a very bad idea as it slows things down, use the standard link syntax and do remember to setup the right media type in it:
<link rel="stylesheet" type="text/css" href="styles.css" media="screen" >

#11: Setup browser caching on your CSS files

Caching on the browser is where you tell the browser that the CSS file is not going to change for a period of time. This could be 1 hour, 1 day, 1 month, 1 year, 100 years or whatever you choose. As long as the browser has not had it’s cache emptied it will re-load your CSS file from it’s local storage and will not ask your server for it. This has 2 distinct benefits, firstly that it loads less files from the server meaning that the server can have more connections at once, and secondly that the CSS file is loaded in miliseconds from the local memory and not 100’s of miliseconds from the server.

Greater details and full instructions for this will come in the “Configuring Servers for Speed” part of this series.

Remember : The browser can only make so many connections at once to the server, it has to wait for each connection to become available before it can be used, going elsewhere than the server allows for the browser to be doing other tasks such as downloading images or HTML.

#12: Use a Content Delivery Network (CDN)

A content delivery network is a global infrastructure of servers that only serve content. The idea being that if your server is located in California and you have a vistor from Germany, then without the CDN they will have to get all of the files from California making lots of extra network time on the trip there and back. However with a CDN the user would not have to go all the way back to California for that information, they would go to the local server in Germany. In fact depending on your CDN hosting company it might be better than just Germany that they go to, if they were for example from Munich then they might go to a Bavarian server.

A content delivery network is really only a viable option to those that have very busy sites, and that is all down to cost. For example the S3 CDN from Amazon web services, the last time I checked, would need a monthly investment cost of $150 minimum and quickly ramping up to very large figures depending on the options chosen. This does place the CDN outside the realm of most websites. However, as a web designer/creator you could invest in a CDN and re-sell that to all of your clients within your hosting package.

Here is a list of top CDN hosting companies…

Akami – The big daddy (or should I say big wave) of all content delivery companies, the first and still the best, but mega bucks to use. Definite corporate choice, very good people to work with, very helpful.

Max-CDN – As used by SpeckyBoy and supported out of the box by the W3 Total cache plugin for WordPress, good pricing.

Highwinds – As used by myself for the Share and Follow plugin for WordPress as it offers security unlike many of the others and great pricing.

Amazon S3 – From Amazon Web Services. Expensive but very good, however, the pricing options do add to the confusion and much time invested to get the right deal.

Limelight – No personal experience with using this CDN, but I have not heard of any bad reports.

Remember : Use a different DNS name than your servers DNS name as the name for your CDN network or it will send pointless cookie info. Don’t use a sub-domain either, it will still send that cookie info.

#13: Try to reduce the usage of Decedent Selectors

Decedent selctors are often used by designers to explicitly define how an element of the page should look. Going back to the example at the top of the page:


.example-footer-1 {
padding:20px;
border-top:solid 1px #cccccc;
border-bottom:solid 1px #cccccc
}
.example-footer-1 ul {list-style-type:none;padding:0;margin:0}
.example-footer-1 ul li {margin-right:3px; display:inline}

(Carriage returns added for readability)
it would infact be much faster to process if setup as:


ul {list-style-type:none;padding:0;margin:0}
li {margin-right:3px; display:inline}
.example-footer-1 {
padding:20px;
border-top:solid 1px #cccccc;
border-bottom:solid 1px #cccccc
}

(carriage returns added for readability)

This is quicker because the browser does not have to keep on looking for .example-footer-1 and it’s decendents when it knows that ul and li have been setup. It’s a ‘set and forget’ method that you have to try to use.

This can be applied to all of your sites design to try to get the most out of the speed of a site, but of course this is a ballancing act between speed and beauty.

#14: Add Things Together to Save Space

Very often in the creation of a website most of the CSS code is duplicated many times throughout the page. So for example there might be a case where the same margins, border and padding is used but a slighlty different tweak made for each one.


.list1 {margin:0; padding:0; border:solid 1px red}
.list2 {margin:0; padding:0; border:solid 1px green}
.list3 {margin:0 5px; padding:0; border:solid 1px black}

where this could be much more efficently written as


.list1, .list2, .list3 {margin:0; padding:0; border:solid 1px red}
.list2 {border-color: green}
.list3 {border-color: black;margin:0 5px}

On a personal level the ones that I tend to do a little different are the rounded corners. Rather than applying them to each CSS element in turn I tend to create 1 or 2 classes that have the rounded corners setup already and apply them to the HTML. For example


.rounded
{-moz-border-radius:3px; border-radius:3px; -webkit-border-radius:3px}

.rounded-big
{-moz-border-radius:15px; border-radius:15px; -webkit-border-radius:15px}

.rounded-top {
-moz-border-radius-topleft:3px; border-top-left-radius:3px;
-webkit-border-top-left-radius:3px; -moz-border-radius-topright:3px;
border-top-right-radius:3px;  -webkit-border-top-right-radius:3px;
}

#15: Combine all of your CSS into 1 file

All web servers and pages work faster when they have a reduced number of connections for each page. So with that in mind it’s much quicker to have only 1 CSS file that is called (gzip’ed, cached and on your CDN) rather than having many. Each request for a new file will take additional time, often will need a DNS lookup, exchange cookie information and have to wait for it’s connection with the server. Cut out all that crap by just adding all your CSS into one file.

#16: Try your hardest to get your CSS file under 25k

If you can get your files to under 25k then iPhone and other mobile devices will cache it. Very important if they are your target audience. If the file is cached it will not be downloaded again.

#17: if you don’t use it don’t send it

Lets imagine that you are creating a site for a Florist and are adapting the Twenty Ten theme for WordPress for it. Can you think of any occasion where the CODE tag is used at all? Nope either can I. So don’t send that CSS to the client. This methodology should also be applied to the CSS reset you might use also, if they don’t use abbr, sub, sub blockquote etc, remove it from your CSS coding. Likewise if the site you are making does not have comments, don’t include all that CSS that deals with comments.

It’s a simple rule but often forgotten, especially when adapting another persons work as your starting point.

#18: Minify your CSS

After you’ve taken the time to do all of the space saving you can, the final thing you would want to do is minify your CSS to make it as small as possible. This is what you should do before officially having production worthy CSS.

There are a few different ways of doing the minification, you can do it before you upload your CSS with tools like this online CSS compressor, a local application on your PC such as YUI Compressor or on the server as a server task which is called each time the CSS file is loaded for a browser. As ever, it’s best to minify first and then upload as there is then less server resources needed to provide the minified file.

Do remember that if you minify it before putting it on your server, it will be impossible more or less to read the file any more.

Roundup

Well, that is the end of this first part of the “Website Speed” series. I will be covering many more items in future editions to give you a well-rounded set of tools to help make things as quick as they can be.

Do remember that every one of these items comes from many years of experience of doing just this, so there is no wasted effort in any of these 18 items. Each one is going to help to make your site faster.

Of course if you can’t wait that long and need someone to a magic speed wand waved over your site, drop me a mail and myself and my team will gladly sort you out on all speed fronts.

The post How to Write More Efficient CSS to Speed up Your Site appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/website-speed-part-1-write-more-efficient-css/feed/ 4