7 Steps to CodeIgniter website speed optimization

The Right Software > Blog > Web Development > 7 Steps to CodeIgniter website speed optimization
7 Steps to CodeIgniter website speed optimization

Website Speed Optimization in Codeigniter

We work as backend software development company for many organizations who have created CMS and online tools from us. For smaller projects, we favor CodeIgniter as its fast and cost-effective. One such project came recently that was already developed by a previous company. The web project was in Code Igniter 2.x but its loading speed was bad. We were engaged by client to fix CodeIgniter website speed optimization.

We are writing this case study to show you what steps were taken to improve website speed. This guide can be for other web-based projects as well.

Before Speed Optimization

Before our changes, the website was languishing at score of 16/100 in Google Pagespeed.

before speed optimization

After Speed Optimization

After our changes, the website score rose considerably to 66/100. Now, its not ideal but its much better than before. To increase more, we need to make changes to the website’s architecture and database. That was out of our scope for this assignment.

After Speed Optimization

Website speed optimization is very much important in today’s world of web because of frequent use of large number of hi-res images, third party API’s and the databases that are keep growing. This is something that should be client’s top priority.

Going on, I will introduce different tools for website speed testing. I will also provide the necessary steps for optimizing website speed.

What information you will need:

In order to optimize the speed of a website, you will need to have access to the ftp, cpanel credentials of the website.

Website speed testing tools

1. Google Pagespeed Insights

Google Pagespeed Insights is the tool provided by Google for testing web pages speed. It gives the results of a page speed for both mobile and desktop version. Apart from this, it also provides detail information about the possible optimizations as well as optimizations that are already applied to a web page. Another cool option provided by this tool, is that it can optimize for you all the images, javascripts and css resources included in the page and provide a download link at the bottom of optimization details. By using these optimized resources, the speed of your web page will increase dramatically.

 

2. Pingdom website speed test

Pingdom is another tool for testing and monitoring webpage performance. Using this tool you can test your website speed from different locations. This tool shows you performance grade of your website, load time, comparison with other websites tested on this tool, page size and number of request made to server. It also provides you with the possible optimizations to be consider for enhancing the performance of a website.

 

3. GTmetrix

GTmetrix is another tool for testing your webpage speed. This tool is based on Google Pagespeed and Yahoo! YSlow rulesets. Using this tool you can track performance of your webpage through monitoring, graphs and alerts.

Steps for CodeIgniter website speed optimization

 

1. Image optimization

Most of the web pages contain bunch of images now a day. If these images are scaled and not properly optimized, it can slow down web page performance. Therefore, it is very much important to use properly optimized images. Do not resize images through css.
Image optimization

 

2. Caching

Every time when you try to access a page, it downloads all the contents from the web server. Using cache mechanism we can tell the browser to use the previously downloaded content instead of downloading the contents from the server again and again. It is therefore advisable to cache the static contents of the page that do not change frequently.

You can implement cache mechanism by adding the following piece code into your .htaccess file.

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"

Of course you can change (i.e. increase or decrease) the access time depending on your requirements.

3. CSS & JS concatenation and minification

Combine and minify your CSS and JS contents. Benefit of combining contents is that the browser will make one request to the server instead of many. While minification reduces the size the file.
There are various tools for combining and minification of contents. PHP Laravel framework comes with built in tool for combining and minification of assets. While you can use GRUNT JS with codeigniter.

To use GRUNT JS, you will need to follow the following steps.

  • Open your command line tool and install npm by running the following commands
    install npm
  • Then install GRUNT by running the following command
    install -g grunt-cli
  • After successful installation, go to your project root directory
    cd {project_root_directory_name}
  • Create gruntfile and package.json files
    touch package.json Gruntfile.js
  • Initialize grunt
    npm init
  • Install grunt plugins
    npm install grunt --save-dev
    npm install grunt-contrib-concat --save-dev
    npm install grunt-contrib-uglify --save-dev
    npm install grunt-contrib-cssmin –save
  • See grunt packages in package.json file
    {
      "name": "project name",
      "version": "0.0.0",
      "description": "",
      "main": "index.js",
      "dependencies": {
        "grunt": "~0.4.5",
        "grunt-cli": "~0.1.13",
        "grunt-contrib-concat": "~0.5.0"
      },
      "devDependencies": {
        "grunt-contrib-concat": "~0.5.0",
        "grunt-contrib-uglify": "~0.7.0",
        "grunt-contrib-cssmin": "~0.11.0"
      },
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "repository": {
        "type": "git",
        "url": ""
      },
      "author": "name of author",
      "license": "BSD-2-Clause"
    }
  • Finally see the grunt task runner in Gruntjs file
    /*
     * grunt-cli
     * http://gruntjs.com/
     *
     * Copyright (c) 2012 Tyler Kellen, contributors
     * Licensed under the MIT license.
     * https://github.com/gruntjs/grunt-init/blob/master/LICENSE-MIT
     */
     
    'use strict';
     
    module.exports = function(grunt) {
     
        grunt.initConfig({
            concat: {
                css: {
                    src: ['assets/css/bootstrap.min.css', 
    			'assets/css/styles.css'],
                    dest: 'assets/css/main.css'
                  },
     
                js: {
                    src: ['assets/css/bootstrap.min.js', 
    			'assets/css/script.js'],
                    dest: 'assets/js/main.js'
                  }
                },
            uglify: {
                js: {
                    src: 'assets/js/main.js',
                    dest: 'assets/js/main.min.js'
                    }
                },
            cssmin: {
                css: {
                    src: 'assets/css/main.css',
                    dest: 'assets/css/main.min.css'
                    }
                }
            });
     
        grunt.loadNpmTasks('grunt-contrib-concat');
        grunt.loadNpmTasks('grunt-contrib-uglify');
        grunt.loadNpmTasks('grunt-contrib-cssmin');
        grunt.registerTask('build', ['concat', 'uglify', 'cssmin']);
    };

You can modify the above file according to your requirements.

For concatenation run: grunt concat
For js minification run: grunt uglify
For css minification run: grunt cssmin
You can also build all at once by running: grunt build

banner hire web development services

4. Content compression

Content compression is an easy and efficient way to save bandwidth and hence speed up your website. Gzip and deflate are the two techniques used for content compression
In codeigniter you can do it by simply setting “compress_output” variable to true in config.php file.

$config['compress_output'] = TRUE;

You can also do it by using your htaccess file. Paste the following lines of code in your htaccess file.

  mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
  mod_gzip_item_include handler ^cgi-script$
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_exclude mime ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

If you want to use deflate mechanism, add the following lines of code to your htaccess file

  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
 
  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent

 

5. Database queries optimization

CodeIgniter runs on MySQL or PostgreSQL database. We can use CodeIgniter’s built-in query caching for caching long-running or arduous queries. The sample syntax is given below. Simple turn db->cache_on before a query and turn db->cache_off after the query returns results.

 

// Turn caching on 
$this->db->cache_on(); 
$query = $this->db->query("SELECT * FROM mytable"); 
// Turn caching off for this one query 
$this->db->cache_off(); 
$query = $this->db->query("SELECT * FROM members WHERE member_id =    '$current_user'"); 
// Turn caching back on 
$this->db->cache_on(); 
$query = $this->db->query("SELECT * FROM another_table");

 

You will still better look into all the SQL queries and find out the time each query takes to fetch the result. For SQL optimization, you should setup slow query log through your web host. You can also check current queries through command

SHOW PROCESSLIST;

Or you can manually test the queries in phpMyAdmin or any database management tool which will show you the time taken by the query to fetch result. If query is fetching too many records, you can lazy load those records, i.e. fetch few records that display on top of the page at the time of page loading while those that appear at the bottom via ajax request. This way your initial page loading time will be decreased. You can also use pagination for this purpose.

 

6. Usage of sprites

A sprite is an image composed of collection of images. Every image on the website makes a request to the web server. So if you are having large number of small images like those used for social icons, cart, login and others. Make a sprite of those images, so to avoid multiple requests to the server. The lesser the number of request to the web server, the faster the speed of the website.

 

7. Reduce server response time

Time taken by the server to respond to a browser request is called server response time. The server response time plays a very significant role in the webpage speed optimization. If you apply all the optimization techniques to your website but the server response time is not good, you will not get the desired results.

Various steps should be taken to reduce server response time, these include using better web hosting services, using less server resources on the website or buying a dedicated server setup such as cloud or VPS.

Conclusion:

So this is all we did for CodeIgniter speed optimization. It is not necessary that all of the above listed steps must be applied in order to optimize the speed of a web page. But depending on a particular case you will need to use a combination of these steps. If you need help with CodeIgniter project, you can contact us.

Pingback

Categories

Free Consultation





Please leave this field empty.

Contact Details

Office # 12,
3rd floor, MB City Mall
I-8 Markaz,
Islamabad, Pakistan.
+92-51-493-8304
hello@therightsw.com

Start a Project with The Right Software