Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.

Website Speed And Performance Optimization | StackCoder

Website Speed and Performance Optimizations

21st November 2020 14 mins read
Share On     Share On WhatsApp     Share On LinkedIn

Nowadays we hear a lot about website optimizations and why it's really crucial for skyrocketing your website performance and generate higher revenue by attracting many customers.

A lot of users use too many non-optimized images, include unnecessary CSS, Javascript libraries, load videos from YouTube or 3rd party hosting sites, don't cache assets, don't use data compression & do many more silly mistakes which results in very bad website experience for end-users.

In this article, we will see different ways to make your website performance blazing fast.

1. Images

A picture is worth a thousand words. More than 50% of the websites that loads slower is mainly because of this little culprit.

We can make the performance of the image faster by implementing the following

  • Resize the images which are very large thus it reduces the image dimensions and reduce the size of an image.
  • Serve the images in next-generation formats ie WEBP or SVG images wherever applicable like logos, social icons which are very lightweight and scale to a bigger screen.
  • Have different image sizes so that you can load them appropriately to different screens with scrset attribute. The medium blog is the best example of the same.

<img alt="Image for post" width="2132" height="531"
    srcset="*UJ54WLMke5RQ4gZcFDxTvQ.png 276w,*UJ54WLMke5RQ4gZcFDxTvQ.png 552w,*UJ54WLMke5RQ4gZcFDxTvQ.png 640w,*UJ54WLMke5RQ4gZcFDxTvQ.png 728w,*UJ54WLMke5RQ4gZcFDxTvQ.png 816w,*UJ54WLMke5RQ4gZcFDxTvQ.png 904w,*UJ54WLMke5RQ4gZcFDxTvQ.png 992w,*UJ54WLMke5RQ4gZcFDxTvQ.png 1000w"

2. Videos

Instead of directly integrating the videos or with 'iframe' from 3rd party platforms in your website, you can first load an image with play icon which impersonates users thinking of video and when the user clicks on the image with the help of Javascript replace the image with actual video and autoplay the video.

Following is the basic implementation of the same.


<div class="col-md-5 col-md-push-7 text-right col-xs-12 featured-image-boy-wrapper">
    <div id="intro-video-wrapper">
        <img src="{{ asset('images/video-placeholder.jpg?cb='.config('wifidabba.cache_busting')) }}" data-video-url="" alt="Wifi Dabba - Laser powered Wifi" class="video-placeholder-image width100">


    var videoImages = document.getElementsByClassName('video-placeholder-image');
    if(videoImages) {
        for(var i = 0; i < videoImages.length; i++){
            videoImages[i].addEventListener('click', function(){
                var iframeUrl = this.getAttribute('data-video-url');
                this.parentElement.innerHTML = '<iframe title="Wifi Dabba - Laser powered Wifi" src="'+ iframeUrl +'" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';

3. Load Only Visible Webpage Images & Videos (Differ Website Images & Videos)

When a user comes to the website we serve all the images and videos irrespective whether he will scroll to the bottom of the website or not. Because of this, there will be some lag in the website.

To overcome this first, we should only load the images of the website which is within the visible viewport width & height. As and when the users scroll down the website we can lazy load the images.

Similar goes for the Videos, when the user scrolls down the website don't load the video directly, just load the image placeholder and when the user clicks on the image load the video and autoplay it as explained in the above point.

4. HTML, CSS & Javascript Minification

Minification is the process of removing the unwanted spaces from the CSS, Javascript & HTML files and thus it compacts the size of the files for faster downloading in the end users browser.

If you are minifying Javascript then nowadays the tools are very powerful, they rename the bigger variable & function names to few letters.

Even there are CSS processors that will rename all your application-wide used CSS class names with the styles with shorter names and compacting it much more. If you inspect the Google Search code then you will surely observe it.

5. Don't Use Lot Of CSS & Javascript Libraries

Most of the time I have seen users use a lot of CSS & Javascript libraries in every page of the website irrespective whether the plugin is required or not for that particular page.

To resolve this kind of issues use CSS & Javascript libraries only to those respective pages. Don't forget to add minified libraries.

Eg: When you’re using Bootstrap CSS Framework then I observed that many developers even thought then don't use Bootstrap Javascript components use bootstrap.js & jquery.js libraries. Few of them load the jQuery library just for the sake of Navigation. Really? Are you kidding me? Just for the sake of navigation.

You can use the following snippet for the same.

HTML For Navigation

<!-- Main Navigation -->
<nav class="navbar navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#top-nav" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            <a class="navbar-brand" href="{{ url('/') }}">
                <img src="{{ asset('images/logo.svg?cb='.config('wifidabba.cache_busting')) }}" alt="WifiDabba" class="logo">

        <div class="collapse navbar-collapse" id="top-nav">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="{{ url('/#') }}">Home</a></li>
                <li><a href="{{ url('/#about-us') }}">About Us</a></li>
                <li><a href="{{ url('/#contact-us') }}">Contact Us</a></li>
                <li><a href="{{ url('/demo') }}" class="btn btn-blue">Book Free Demo</a></li>

Javascript implementation for Navigation

    /** Navigation toggling */
    var toggleButton = document.querySelector('.navbar-toggle');
    var navigationContainer = document.querySelector('#top-nav');
    toggleButton.addEventListener('click', function(){

    /** On click of any link then close the navigation */
    var menuItems = document.querySelectorAll('#top-nav ul a');
    for(var i = 0; i < menuItems.length; i++){
        menuItems[i].addEventListener('click', function(){

6. Remove Unused CSS & Javascript

Think that you’re using the Bootstrap library for the website design. Almost all the time you might not use all the styles of it on your website. So now you can open bootstrap.js file and remove the unnecessary styles that you don't need.

Nowadays almost every CSS framework use SASS or LESS thus you can directly customize the features that you don't need and recompile them as per your needs.

Similar goes for the Javascript.

7. Cache Busting (Cache Assets like CSS, Javascript, Images etc.)

The webpage loading speed can be made faster by caching your website static files like Images, Stylesheets, Javascripts, Fonts, HTML page and many more in clients devices with the following simple technique.


location ~* \.(svg|gif|otf|jpg|jpeg|png|css|js|ttf)$ { # Anything that ends with .gif .jpg .jpeg .svg .css .js I want to cache
    add_header Cache-Control public; # Cache control header for browsers
    add_header Pragma public; # Cache control header for browsers
    add_header Vary Accept-Encoding; # Cache control header for browsers
    expires max; # Store the static files as long as possible this will be more than a year.

For detailed implementation kindly check this article Cache Static Files With NGINX Server

8. GZip Compression

When a user visits your website a call is made to your server to deliver the requested files. If the files are bigger then it takes a long time for user browser to download the files and make them appear on the user’s browser screen.

With the help of Gzip compression, the server will compress your webpages and CSS, Javascript and many other files before sending them to the user browser. This drastically reduces transfer time since the files are much smaller.

Gzip In Apache .htaccess (Make sure to download mod_gzip)

<ifModule mod_gzip.c>
  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.*

Gzip In Nginx

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 8;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

9. Hotlink Protection

A hotlinking is a process of restricting our website images, static assets (CSS, Javascript, Fonts, etc.) to other websites that are not related to us. Because of this, our website performance will reduce drastically. Every time the other user's website loads it will pull the resources from our website.

No need to worry as we can prevent it with the following method

Implement in Nginx Web Server

valid_referers none blocked *;
if ($invalid_referer) {
    return   403;

Full implementation snippet in Nginx Web Server

location ~* \.(gif|otf|jpg|jpeg|png|css|js)$ {
    valid_referers none blocked *;
    if ($invalid_referer) {
        return   403;
    add_header Cache-Control public;
    add_header Pragma public;
    add_header Vary Accept-Encoding;
    expires max;

10. Use CDN (Content Delivery Network)

Try using CDN assets as much as possible, as the servers will be located in different parts of the world and their services will be synced across the servers it will serve the contents faster for the users. Thus improving the website performance.

11. Ensure Text Remains Visible During Webfont Load

Even after caching fonts sometimes when you run an audit in Google Lighthouse, you will basically encounter Ensure text remains visible during Webfont load.

This is because some browsers wait for the fonts to get loaded and don't show texts in the browser until they load the Webfont. You might have imported the font-family as below.

@font-face { 
    font-family: inter; 
    src: url('../fonts/Inter-Regular.otf'); 

One simple way to tell browsers to show the default one text and don't wait for fonts to load is to add the following code.

font-display: swap;

Now your overall CSS will look like the following

@font-face { 
    font-family: inter; 
    src: url('../fonts/Inter-Regular.otf'); 
    font-display: swap;

You can read more on it at Ensure text remains visible during Webfont load

12. Add HTTP2 Support

In 2015, the Internet Engineering Task Force (IETF) released HTTP/2. It was derived from the earlier experimental SPDY protocol.

Main goals of developing HTTP/2 was:

  • Request multiplexing over a single TCP connection (All resources are loaded simultaneously at a time).
  • Protocol negotiation mechanism — protocol electing, eg. HTTP/1.1, HTTP/2 or other.
  • High-level compatibility with HTTP/1.1 — methods, status codes, URIs and header fields.
  • Page load speed improvements
  • Compression of request headers
  • Binary protocol
  • HTTP/2 Server Push
  • Request pipelining
  • HOL blocking (head-of-line) — Package blocking

Once you install an SSL certificate in your application by default it doesn't support the HTTP2 standards. We need to explicitly enable it.

Enabling HTTP2 In NGINX Server

listen 443 ssl http2;

Partial Code implementation will look like the following

listen 443 ssl http2; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

To read more on HTTP2 please read this article HTTP/2: the difference between HTTP/1.1, benefits and how to use it

13. Turn Off Access Logs

Access logs are the list of all the requests URL's that gets logged when users visit any of your website pages. Many times there won’t be any limit to this kind of logs thus it might fill up the sever space very soon.

Since these will get logged every time a user requests your website server it will take some minute time to logs the URL. Hence it is highly suggested to turn off the access logs if not required.

14. Reduce The Website Shift

When a user comes to your website and during the time of loading, if you have images in your website and if the image width and height attributes are not specified within the img element and only given in CSS style then during loading there won’t be any fixed width and height occupied by the image and content will load immediately.

By the time users is about to read the content the image loads then there is a sudden shift of the website content down.

15. Always Use HTTPS Protocol

HTTPS adds up a round trip from the users browser to the server for securing all the connection which might impact in a very very minute millisecond. But its really worth to add as it provides more privacy & security of the users content and HTTP2, HTTP3 can be enabled very easily.

16. Don't Use Javascript Inside head Tag

Don't load any of the Javascripts in the head tag of your website. Since the browsers read the HTML code line by line, as soon as it comes across Javascript it will start processing it which might take some time.

Hence the best advice is to load them before the end of the <body> tag

17. Reduce The Use Of WebFonts

When we compare the year 2012 to 2020 custom WebFonts usage has increased beyond 700%. Because of this, we have to load the respective libraries which will impact the performance of websites.

Hence even if we try to use it, make sure to lazy load it or use Ensure Text Remains Visible During Webfont Load so that the performance will be increased slightly.

18. Remove PopUps & Content Blocking Ads

A lot of times website loads with too much of popups or content blocking ads because of which it might take some time to load another important resource of the website and impact the website speed.

19. Database Query Optimizations

Most of the times you might not only have a static website but have some dynamic content that you fetch from the database or write to the database. While doing these if you don't think of the database query optimizations then sooner your database data size grows the slower your website starts behaving.

Few of the steps how you can optimize the queries are as follows

- Fetch only the necessary columns when you query


  id = '6ab704ed-d58f-3935-b859-459ecd3c61fc';


  name, featured_image, view_cout, body 
  id = '6ab704ed-d58f-3935-b859-459ecd3c61fc';

- Limit the number of rows you fetch at a time




LIMIT 1, 10;    

- Log the queries that are taking too much time to execute

- Use DISTINCT and UNION when required

- Try avoiding SubQueries as much as possible and use Joins

- Use 'Explain' along with the query to check how your bigger queries are performing

20. Application, Database Caching

Cache cache cache, I tell a lot of my friends and juniors to cache the Application Configurations (Opcode Cache, Mem Cache), Database Queries (Redis) so that the frequently used resources of your website are served faster for your customers.

21. Reduce HTTP Redirects

If you do a lot of temporary (302) or permanent (301) redirects in your application then it makes take some time to redirect to the actual page and making feel the website lag for your potential customers.

22. Use Latest Versions Of Software & Libraries

Make sure to use the latest software versions so that there will lot of performance, security and bug fixes which help your website load faster, perform better and safe guard against lof of vulnerabilities and hacks.

Eg: Till now most of them use PHP5.6 whereas the latest release is PHP7.4 which is much secure and performs 2x than PHP5.6

If you really care about the server security then don't forget to check this article How To Do Basic Server Security Setup For Ubuntu / Linux

23. Use Proper Server Infrastructure

It's not a bad idea to go with Shared Hosting ie cPanel, but if you need flexibility & performance for your application & if see a lot of customer traction in your website then better to switch to VPS Servers (Virtual Private Servers) like Google Cloud Platform, Amazon AWS, Digital Ocean, Linode etc. which will provide services in different countries around the globe but also gives you the dedicated CPU, Memory, Server space, High Availability and you can scale your application by upgrading the infrastructure when necessary with Load Balancers, CPU, Memory, Space and downgrade when not needed.

If you would like to use advanced auto deployments for your projects with the help of DevOps technologies like Kubernetes, Docker, GitHooks etc. then you should definitely give a try to VPS servers.


Hope you enjoyed the article. Please do share with your friends.

Author Image

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing