Why the Why is Important in Software Development

Ever found yourself knee-deep in code, wondering why you’re building what you’re building? 🤔 It’s like planning a road trip without knowing the destination. It may sound fun at first but after sometime you will regret your decision. But here’s the thing – too often we get so caught up in the nuts and bolts of HOW to build something that we forget to ask WHY we’re building it in the first place. This is what I’m gonna discuss-why asking this question ‘why’ can make you an achiever.” Here is why asking ‘why’ is the secret behind all successful projects and saves you from spending all your time debugging as well as will reduce your project to an endless goose chase.

The Power of “Why”

The “why” isn’t just a question; it’s the North Star that guides your project. When you understand the underlying reasons, you can make informed decisions that keep you on track. It’s like knowing the plot twist before watching the movie—you see the bigger picture.

Imagine a team working on a new mobile app feature. If they know the goal is to boost user engagement, they can focus on creating interactive elements, rather than adding random functionalities. Knowing the “why” turns chaos into clarity.

Developers ignoring the “why”

Integrating “Why” into the Design Process

Design thinking is where the magic happens. It’s like putting on a detective hat and solving a mystery—why do users need this feature? This user-centered approach makes sure your software isn’t just pretty, but also practical.

  • Empathy Mapping: Get into your users’ shoes. Understand their needs, motivations, and pain points. Bonus points if you actually try their favorite coffee order.
  • User Personas: Create detailed profiles of your target users. Think of them as your project’s spirit animals.
  • Prototyping and Testing: Build prototypes and test them. It’s like baking a cake—you want to taste it before serving it to guests.

By starting with “why,” you make sure your design process is aligned with real user needs, not just your whims.

Remember Spotify’s Discover Weekly? It’s not just a playlist; it’s a game-changer. Spotify didn’t just randomly decide to create this feature. They asked, “Why do users need help discovering new music?” The answer was simple: users were drowning in a sea of songs.

By understanding this, Spotify’s team created an algorithm that curates a personalized playlist every week. It’s like having a personal DJ who knows your taste better than you do. The result? Users are hooked, and Discover Weekly became a massive hit.

Case Study: Successful Project

Let’s dive into a real-world success story. A tech company aimed to develop a new customer relationship management (CRM) system. Initially, they were all about loading it with the latest features. But then, someone asked the golden question: “Why do we need this system?”

Turns out, the primary goal was to improve customer retention through personalized service. This insight shifted their focus from feature overload to creating a system that provided valuable customer insights. The result? A CRM that skyrocketed customer satisfaction and retention rates.

Key Takeaways:

  • Understanding the “why” can shift the focus from feature frenzy to solving real problems.
  • It leads to better decisions and more impactful outcomes.

Unsuccessful Project

Now, let’s look at a cautionary tale. A startup decided to launch a new social media platform. Excitement was high, and they dove into development, adding every feature imaginable. But they forgot to ask, “Why would users choose our platform?”

Without a clear “why,” the platform launched with great fanfare but quickly fizzled out. Users didn’t see the unique value, and the platform faded into obscurity.

Lessons Learned:

  • Neglecting the “why” can lead to a product that flops.
  • Asking the right questions early on can save time, resources, and heartache.

Practical Tips for Asking the Right Questions

So, how can you ensure you’re asking the right questions? Here are some practical tips:

  1. Start with the Basics: Ask fundamental questions like “What problem are we solving?” and “Who are we solving it for?” It’s like making sure you packed your snacks before a road trip.
  2. Engage Stakeholders: Involve different perspectives to uncover various aspects of the “why.” It’s like hosting a potluck—everyone brings something valuable to the table.
  3. Iterate and Reflect: Continuously revisit the “why” as the project evolves to ensure alignment with goals. Think of it as your project’s GPS.
  4. Document and Share: Keep a record of the “why” and make it accessible to the entire team to maintain focus. It’s your project’s guidebook.

The Broader Impact

Understanding the “why” doesn’t just improve individual projects; it enhances overall team collaboration and product quality. When everyone is on the same page, it’s easier to work together towards a common goal. This alignment fosters a more cohesive team environment and can lead to more innovative solutions.

Moreover, a clear understanding of the “why” can ripple outwards, influencing company culture and leading to a more purpose-driven organization. When teams are aligned with the bigger picture, they are more motivated and engaged, which translates into better products and happier customers.

Conclusion

In the realm of software development, the “why” is a powerful tool. It provides direction, purpose, and clarity, ensuring that the efforts of a development team are meaningful and impactful. By taking the time to ask the right questions and understand the underlying reasons for a project, you can avoid common pitfalls and set your projects up for success. So next time you start a new project, take a moment to ask yourself: “Why are we doing this?” The answers might just lead you to better outcomes.

Cloud-Native Chaos: How to Navigate through

Alright cloud ninjas, let’s be honest. Does anyone else feel like “cloud-native” has become the tech industry’s version of the latest fashion trend? Everywhere you turn, there’s another tool, another framework, another “must-have” for your cloud architecture. It’s enough to make your brain hurt.

Don’t get me wrong please, I’m all for innovation. But between the constant vendor hype and the ever-shifting trends, we engineers are left feeling like hamsters on a tech trend wheel. Is anyone else with me on this?

We’ve got senior devs (you know, the 7-10 year veterans) scratching their heads as the pendulum swings back from “cloud everything” to a mix-and-match approach. And new engineers fresh out of boot camp? They’re drowning in a sea of conflicting advice and confusing abbreviations.

Today’s cloud-native world is full with confusion, and it’s no wonder why. The sheer volume of tools and conflicting advice makes it hard to know where to turn. A quick Google search shows ten different answers to the same question, leaving engineers more bewildered than enlightened. The cloud-native space is evolving at breakneck speed. We crave more, faster, reflecting modern consumerism’s insatiable appetite. This rapid development pace, combined with a plethora of vendors, complicates matters further.

To illustrate how many of us feel, here’s a popular meme that perfectly captures the current state of cloud-native development:

Credit: dailydot

Too Many Tools

The tool landscape is overcrowded. Where once Active Directory was the go-to for authentication and authorization, we now have over ten alternatives, each with slight differences. This surplus of options is paralyzing.

The Paradox of Choice

When faced with too many options, our natural reaction is often to choose none. This phenomenon, known as “choice overload,” leaves engineers feeling overwhelmed and directionless.

Finding the Fix

Addressing this confusion and tool overload is challenging but feasible. Here’s a structured approach to mitigate these issues.

Reducing Confusion

Start by asking a single, crucial question: What’s the expected outcome?

Consider this scenario: Engineer A, excited by the Kubernetes hype, implements it without understanding its necessity, resulting in tech debt. Engineer B, however, asks about the expected outcome and then tailors a solution—Kubernetes or otherwise—to meet that goal. By focusing on outcomes, Engineer B avoids unnecessary complexity and chooses tools that align with specific needs.

Streamlining Tool Selection

Here’s a three-step approach to tackle the tool dilemma:

  1. Identify the Outcome: Begin by understanding the expected outcome, which helps in narrowing down the tool options.
  2. Research Thoroughly: Look into the tools that match your needs. Consult forums, read reviews, and gather opinions, but remember to take them with a grain of salt.
  3. Evaluate Rigorously: Test 2-3 tools extensively. Spend 3-4 days evaluating each one, paying attention to ease of installation, scalability, and usability.
  4. Strategic Tool Selection: Not a One-Size-Fits-All Deal.

My Perspective

As an experienced developer in multi-cloud enterprise architecture, I’ve seen firsthand how overwhelming cloud-native confusion and tool overload can be. I’ve found that the key to cutting through the noise is to focus on the essentials:

  • What is the objective? Define clear goals for what you want to achieve.
  • How do we reach that efficiently? Develop a straightforward, efficient plan to meet your goals.
  • How do we keep operating and running the system, at best automatically? Aim for automation to ensure smooth, ongoing operations.
  • How easy is it to change or add something? Ensure that your system is flexible enough to accommodate future changes.

It’s also crucial to get hands-on experience. Try out different solutions, build prototypes, and thoroughly test them before making a final decision. Avoid relying solely on procurement departments without knowing exactly what you need, as this can lead to unnecessary vendor conflicts and wasted resources.

What are your thoughts, cloud comrades? How do you cut through the noise and make sound decisions in the ever-evolving cloud-native landscape? Are there any tools or strategies you swear by? Let’s chat in the comments!

Using Amazon S3 Bucket with Node.js: A Step-by-Step Guide

Amazon S3 (Simple Storage Service) is a popular object storage service offered by Amazon Web Services (AWS) that allows you to store and retrieve any amount of data from anywhere on the web. In this guide, we will walk you through the process of integrating Amazon S3 Bucket with Node.js to handle file uploads and downloads.

Prerequisites

Before you begin, make sure you have the following:

  1. An AWS account with access to S3 services.
  2. Node.js and npm (Node Package Manager) are installed on your machine.

Step 1: Set Up AWS Credentials

To interact with AWS services, you’ll need to configure your AWS credentials on your development environment. You can do this by using the AWS CLI or by manually creating a ~/.aws/credentials file. Replace YOUR_ACCESS_KEY and YOUR_SECRET_KEY with your actual AWS access and secret keys.

[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

Step 2: Create an S3 Bucket

Log in to your AWS console and navigate to the S3 service. Create a new bucket by clicking the “Create bucket” button. Follow the prompts to choose a unique bucket name and configure other settings.

Step 3: Set Up Your Node.js Project

Create a new Node.js project (or use an existing one) and install the AWS SDK using npm:

npm install aws-sdk

Step 4: Use AWS SDK to Interact with S3

Upload a File to S3

In your Node.js file, require the AWS SDK and create a new instance of the S3 service:

const AWS = require('aws-sdk');
const fs = require('fs');

// Configure AWS SDK
AWS.config.update({region: 'us-east-1'}); // Change to your desired region

const s3 = new AWS.S3();

// Define the parameters for the upload
const params = {
  Bucket: 'your-bucket-name',
  Key: 'example.jpg', // Name of the file in S3
  Body: fs.readFileSync('path/to/local/file.jpg') // Local file to upload
};

// Upload the file
s3.upload(params, (err, data) => {
  if (err) throw err;
  console.log('File uploaded successfully.', data.Location);
});

Download a File from S3

To download a file from S3, use the getObject method:

const params = {
  Bucket: 'your-bucket-name',
  Key: 'example.jpg' // Name of the file in S3
};

s3.getObject(params, (err, data) => {
  if (err) throw err;
  fs.writeFileSync('downloaded.jpg', data.Body);
  console.log('File downloaded successfully.');
});

Step 5: Test Your Code

Run your Node.js file using node your-file.js and ensure that the file is uploaded and downloaded successfully.

Congratulations! You’ve successfully used Node.js to interact with Amazon S3 Bucket. You can now build applications that utilize S3 for file storage and retrieval.

Remember to manage your AWS credentials and access permissions carefully to ensure the security of your S3 resources. Happy coding!

Don’t forget to check other posts on AWS 😉

spring-boot-hateoas-for-restful-services

Spring Boot – HATEOAS for RESTful Services

In this article, I will explain implementing HATEOAS for a REST API with Spring Boot with an example.

What is HATEOAS?

HATEOAS stands for “Hypermedia as the engine of application state”

It’s a complicated acronym. Let me decode it for you.

What do you visualize when you visit a web page?

The data that you would want to see. Is that all? You would also see links and buttons to see related data.

For example, if you go to a product page, you will see

  • product details
  • Links to Edit and Delete product details
  • Links to see relevant products in that category

HATEOAS brings the exact same concepts to RESTful Web Services.

When some details of a resource are requested, you will provide the resource details as well as details of related resources and the possible actions you can perform on the resource. For example, when requesting information about a Facebook user, a REST service can return the following

  • User details
  • Links to get his recent comments
  • Links to retrieve his friend list
  • Links to get his recent posts

Sigh, a lot of things to read right? Let’s, get our hands dirty =D

Create the project

Create a new project using start.spring.io

Add basic CRUD Operation

I’m not gonna explain CRUD operation in detail, you can refer to my project uploaded on Github.

Enhancing the resource

To implement HATEOAS, we would need to include related resources in the response. Instead of Product, I’ll use a return type of EntityModel<Product>. EntityModel is a simple class wrapping a domain object and allows adding links to it.

@GetMapping("/{id}")
public EntityModel<Product> getProduct(@PathVariable long id) {
    Optional<Product> product = productRepository.getProductById(id);

    if (!product.isPresent())
        throw new ProductNotFoundException("id-" + id);
    EntityModel<Product> resource = EntityModel.of(product.get());
    WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).getAllProducts());
    resource.add(linkTo.withRel("all-products"));
    return resource;
}

So what’s happening here actually?

EntityModel<Product> resource = EntityModel.of(product.get());

In the above line, we are creating a new resource. Then, adding the link to retrieve all products method to the link.

WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).getAllProducts());
resource.add(linkTo.withRel("all-products"));

In the above line, we are creating a new resource. After making the changes so far, let’s start the service and see the change in action.

{
    “id”: 1,
    “name”: “Dell Precision 5550”,
    “currentStock”: 99,
    “description”: “The world’s smallest and thinnest 15 inch mobile workstation.”,
    “type”: “Laptop”,
    “dateCreated”: “2022-10-23T08:33:10.658+00:00”,
    “lastModified”: “2022-10-23T08:33:10.658+00:00”,
    “_links”: {
        “all-products”: {
            “href”: “http://localhost:3001/api/v1/product”
        }
    }
}

Don’t worry, I’ve added a bootstrap class to add a few products into the DB whenever the application starts.

The above example covers important concepts in enhancing resources with HATEOAS.

However, ain’t gonna make this post longer. You have to make the important decisions:

  • What are the important resources related to a specific resource?

Think of this as homework, go ahead and enhance the application with more HATEOAS links.

Oh! I forgot to give you the Github link, Here you go: https://github.com/nazrul-kabir/spring-boot-rest-service-with-hateoas Feel free to comment on the post if you have any comments.

And, don’t forget to read my other posts on Spring Boot

Writing Complex Queries Using LINQ

I am writing this article based on my recent experience regarding how to write some complex queries using LINQ.

I’m not going to explain why we should use LINQ over lambda or neither Query Syntax vs. Method syntax in LINQ.

Let’s dig in..

LINQ Join column from 2 table:

Just for the demo, I have created Building & Resource classes. Resource having a relationship with Building via BuildingId column.

Now I have to write a query that returns ‘Distinct’ and ‘Active’ resources list i.e: Resource Id & Resource Name- Building Name. Ex: Physics Lab-Building 01. Here ‘Lab’ is the Resource Name and ‘Building 01’ is the Building name.

IdName
100Physics Lab-Building 01
101Chemistry Lab-Building 02
var resourcequery = (from resource in DbInstance.Resource
join building in DbInstance.Building on resource.BuildingId equals building.Id
where resource.IsActive == true
select new { resource, building } into t1
select new
{
Id = t1.resource.Id.ToString(),
Name = t1.resource.Name + "-" + t1.building.Name
}).Distinct().ToList();

Here is the final output:

Difference Between Coding & Programming?

Last week one of my university juniors asked me this question! That, what’s the difference between Coding & Programming?

Then I thought I should write a post about it and try to explain. I believe it’s very important if you are working Software Industry you should know what you actually are!

Most people think both are the same thing! Not at all! There are differences between the two “worlds”. So let’s explore how professionals use them and try to understand the terms first by understanding what they mean.

What’s Coding?

Image courtesy: unsplash

Coding is how we communicate with computers. Code tells a computer what actions to take and writing code is like creating a set of instructions.
In order to become a coder, you need to be able to write code in different programming languages such as Java, C, PHP & so on. With this knowledge, you will be able to provide instructions and information to the computer to execute the programs you or your team creates.

Coding involves writing code for creating a software program or any sort of application, website, game.

What’s Programming?

Image courtesy: pexels.com

There are many definitions of what programming is, but the one I prefer is: “Programming is how you get computers to solve problems.” There are two key phrases here which is important:

  • you: without the programmer (you), the computer is useless. It does what you tell it to do.
  • solve problems: computers are tools. They are complex tools, admittedly, but they are not mysterious or magical: they exist to make tasks easier.

In order to come up with a solution or an application, you will need to carry out a few steps:

  • planning the application
  • designing it
  • testing the features
  • deploying it
  • maintaining it after development is finished

So it’s only fair to say that programming not only deals with coding but also implementing algorithms and much more.

Let me try to explain it in a simpler way so you can get a better understanding.

For example, you can program your watch to wake you up at 7 AM. Also, you can program the AC to come on at the temperature that you have chosen. These devices have code on the backend that works based on a set of instructions given by the user.

The Differences Between Coding and Programming in Brief:

  1. Basic Difference:
    Coding is a part of programming that deals with writing code that a machine can translate. Programming is the process of creating a program that follows certain standards and performs a certain task.
  2. Scope:
    Coding is about translating the requirement logic into machine-understandable code. In contrast, programming demands analysis and conceptualization of different aspects of any program and finding solutions to any issues that may occur during the process. It also involves critical parameters such as debugging, compiling, testing, and implementation.
  3. Tools:
    Coding doesn’t require as many software tools since it’s just an act of code translation to machine-readable form. Just a simple text editor like notepad or WordPad is enough. As a coder, you just need to know the details of the syntax of any programming language.
    Programming requires that you perform document reviews and analysis along with coding that requires extra tools. These tools include code analyzing tools, databases, testing frameworks, compilers, assemblers, debuggers, and modeling algorithms. A programmer needs lots of experience to obtain these skills.
  4. Expertise:
    Coders should have basic knowledge of programming.
    Programmers should have experience in creating algorithms, understanding requirements, processing data, modeling problems, and managing projects – these are just some of the practical skills needed.
  5. Outcome:
    While coding, your expected outcome is part of or the whole project. The code acts as a set of instructions given to the computer.
    On the other hand, programming yields the whole application, software products, or a website that’s ready to use.

So, how both Coding and Programming works together?

Let’s explain this using an example to get a better understanding. Imagine we are creating an app to monitor something like our daily routine for us. How will these two different fields work together?

First the programmer will have to:

  • plan the architechture of the app,
  • list down features of the app
  • designing the app

After the programmer is done with these first steps, they hand it over to the coder.
Now the coder will transform the ideas into code. After this process is done, the completed code is given back to the programmer.

Now the programmer will go through the code do some polishing by debugging, checking for errors, and doing tests before publishing the final product.
Now you can see how these two fields have come across together to work on an idea and produce something that’s usable.

Final Words:

Often people confuse programming & coding; hope by now you agree that they are distinctively different after comparing coding vs. programming with a number of factors.

Coding is the primary step and translates the requirements and codes to convert into a machine-readable syntax. Still, programming deals with the executable programs to produce the mechanical outputs following the inputs and requires the knowledge of the complete software development life cycle.

WooCommerce: Add a New Tab in My Account Page

Are you looking for a straight way to add a new tab in my-account page in WooCommerce that can be implemented quickly and easily by any WooCommerce user irrespective of their level of skill?

Today, I’m going to show you how to add a custom tab on the WooCommerce My Account page – feel free to leave a comment below if you found this tutorial useful 🙂

 

To add a new tab in the WooCommerce my-account page, it entails four steps as follows:

  1. Create a filter hook to add the new tab in my-account page and the filter should gather all the data that is displayed on the menu and then push in your new data.
  2. Create a second filter that adds the URL redirect of the menu you added in the first step to the page you have created just now.
  3. Adding the new endpoint under the Account menu
  4. Add this code to your theme’s functions.php file or you can add this code to a plugin class or function and you will successfully add the new menu on my account page in WooCommerce.
  1. Add the First Filter to Add Menu to My-Account Page
// Note: Resave Permalinks or it will give 404 error
function myaccount_add_notification_endpoint() {
    add_rewrite_endpoint( 'notification', EP_ROOT | EP_PAGES );
}
add_action( 'init', 'myaccount_add_notification_endpoint' );

This gonna create the new endpoint “notification” the new menu on my account page.

2. Add Second Filter to Add Menu to My-Account Page

function myaccount_add_notification_query_vars( $vars ) {
    $vars[] = 'notification';
    return $vars;
}
add_filter( 'query_vars', 'myaccount_add_notification_query_vars', 0 );

3. Insert the new endpoint into the My Account menu

function myaccount_add_notification_link_my_account( $items ) {
    $items['notification'] = 'Notification';
    return $items;
}
add_filter( 'woocommerce_account_menu_items', 'myaccount_add_notification_link_my_account' );

4. Add content to the new endpoint

function myaccount_add_notification_content() {
echo '<h3>Welcome to the new page</h3>;
echo do_shortcode( ' /* your-shortcode-here */ ' );
}
add_action( 'woocommerce_account_notification_endpoint', 'myaccount_add_notification_content' );
// Note: add_action must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format

Wrapping Up! You can find the whole code at the end of the post 😉
Adding a new menu tab in my-account page on WooCommerce should not be a challenge anymore after reading this tutorial. I have tried to explain step-by-step and with a practical example on how to add a new tab in my-account page and add the content of your choice. I have also written other tutorials on how to show Store(Vendor) Name on Checkout page in WordPress and add a checkbox in checkout page for customer whether wants to be a member & send customer details to email.

PHP snippet: How to Add a New Tab in My Account Page

// How Use => Add the below function in your theme's functions.php file
// Output  => https://snipboard.io/dDeMmK.jpg
/**
 * @snippet       WooCommerce Add A New Tab In My Account
 * @author        Nazrul Kabir(www.nazrulkabir.com)
 * @compatible    WooCommerce 3.5.7+
 */
// ------------------
// 1. Register new endpoint to use for My Account page
// Note: Resave Permalinks or it will give 404 error
function myaccount_add_notification_endpoint() {
    add_rewrite_endpoint( 'notification', EP_ROOT | EP_PAGES );
}
add_action( 'init', 'myaccount_add_notification_endpoint' );
// ------------------
// 2. Add new query var
function myaccount_add_notification_query_vars( $vars ) {
    $vars[] = 'notification';
    return $vars;
}
add_filter( 'query_vars', 'myaccount_add_notification_query_vars', 0 );
// ------------------
// 3. Insert the new endpoint into the My Account menu
function myaccount_add_notification_link_my_account( $items ) {
    $items['notification'] = 'Notification';
    return $items;
}
add_filter( 'woocommerce_account_menu_items', 'myaccount_add_notification_link_my_account' );
// ------------------
// 4. Add content to the new endpoint
function myaccount_add_notification_content() {    
    echo '<h3>Notification List</h3>';
    echo do_shortcode( ' /* your-shortcode-here */ ' );
}
add_action( 'woocommerce_account_notification_endpoint', 'myaccount_add_notification_content' );
// Note: add_action must follow 'woocommerce_account_{your-endpoint-slug}_endpoint' format

If you’ve any confusion please let me know 🙂

How to show Store(Vendor) Name on Checkout page in WordPress

So, this was the requirement from the client to show the Vendor Name on the Checkout page. Though the plugin shows the Vendor Name of each product on the right side just after the product name.
N.B: To support multi-vendor in WordPress I’m using Dokan Plugin.

How-to-print-store-name-in-multivendor-woocommerce-wordpress

Let’s copy the code from below:

add_action( 'woocommerce_before_checkout_form', 'print_vendor_name_on_checkout_page', 10 );
function print_vendor_name_on_checkout_page()
{
echo 'Shop: ';
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
$authror_id = $cart_item['data']->post->post_author; // <=== The post author ID
$author = get_user_by( 'id', $authror_id );
$store_info = dokan_get_store_info( $author->ID );
$store_title= $store_info['store_name'];
}
if ( !empty( $store_title ) ) { ?>
<span class="details">
<?php echo $store_title; ?>
</span>
<?php }
}

That’s all! We’re done!
N.B.: In my case customers are allowed to order from one shop/vendor at once. That’s why I’ve printed the shop name outside the foreach function.

So, what if in your case you allow ordering from multiple stores? Just print the store name inside the foreach!

add_action( 'woocommerce_before_checkout_form', 'print_vendor_name_on_checkout_page', 10 );
function print_vendor_name_on_checkout_page()
{
echo 'Shop: ';
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
$authror_id = $cart_item['data']->post->post_author; // <=== The post author ID
$author = get_user_by( 'id', $authror_id );
$store_info = dokan_get_store_info( $author->ID );
$store_title= $store_info['store_name'];
if ( !empty( $store_title ) ) { ?>
<span class="details">
<?php echo $store_title; ?>
</span>
<?php }
}
}

Done! Pretty simple, isn’t it?

Lightweight YouTube Embeds – A Better Approach for Embedding YouTube Videos on your Site

     

Have you ever checked how much extra data a single embedded YouTube video can add to your web pages.

It’s easy to embed a YouTube video but have you ever checked how much extra data a single YouTube video can add to your web pages. The browser has to download nearly 800 KB of data (see screenshot below) for rendering the YouTube video player alone! And these files are even downloaded before the visitor has clicked the play button.

Only the base.js itself adds 492KB data! In total 23 requests are made and downloads ~800 KB data even before the play button is clicked! Don’t believe? See it in action here.

This increases the overall loading time of your page thus affecting the page speed. The other drawback with the default YouTube embed code is that renders a video player of fixed dimensions and isn’t responsive. If people view your website on a mobile phone, the video player may not resize properly for the small screen.

Normal YouTube Embed Video:

The standard embed code for YouTube uses the IFRAME tag(Google+ technique) where the width and height of the video player are fixed(may be you can write some custom CSS to make responsive) thus making the player non-responsive.

So, I’ve been looking for a solution so that the weight of the page doesn’t goes up. Finally found a solution!

Step-1:
<div class="youtube-player" data-id="VIDEO_ID"></div>
Step 2:
Copy-paste the below JS anywhere in your web page. The script finds all embedded videos on page and then replaces the DIV elements with the video thumbnails and a play button (see demo in action).

<script type=”text/javascript”>

function myIframe(div) {
var iframe = document.createElement(‘iframe’);
iframe.setAttribute(
‘src’,
‘https://www.youtube.com/embed/’ + div.dataset.id + ‘?autoplay=1&rel=0’
);
iframe.setAttribute(‘frameborder’, ‘0’);
iframe.setAttribute(‘allowfullscreen’, ‘1’);
iframe.setAttribute(
‘allow’,
‘accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture’
);
div.parentNode.replaceChild(iframe, div);
}

function initYouTubeVideo() {
var playerElements = document.getElementsByClassName(‘youtube-player’);
for (var n = 0; n < playerElements.length; n++) {
var videoId = playerElements[n].dataset.id;
var div = document.createElement(‘div’);
div.setAttribute(‘data-id’, videoId);
var thumbNode = document.createElement(‘img’);
thumbNode.src = ‘//i.ytimg.com/vi/ID/hqdefault.jpg’.replace(
‘ID’,
videoId
);
div.appendChild(thumbNode);
var playButton = document.createElement(‘div’);
playButton.setAttribute(‘class’, ‘play’);
div.appendChild(playButton);
div.onclick = function () {
myIframe(this);
};
playerElements[n].appendChild(div);
}
}document.addEventListener(‘DOMContentLoaded’, initYouTubeVideo);
</script>

Step 3:

<style rel=”stylesheet”>
.youtube-player {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
max-width: 100%;
background: #000;
margin: 5px;
}
.youtube-player iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 100;
background: transparent;
}
.youtube-player img {
object-fit: cover;
display: block;
left: 0;
bottom: 0;
margin: auto;
max-width: 100%;
width: 100%;
position: absolute;
right: 0;
top: 0;
border: none;
height: auto;
cursor: pointer;
-webkit-transition: 0.4s all;
-moz-transition: 0.4s all;
transition: 0.4s all;
}
.youtube-player img:hover {
-webkit-filter: brightness(75%);
}
.youtube-player .play {
height: 72px;
width: 72px;
left: 50%;
top: 50%;
margin-left: -36px;
margin-top: -36px;
position: absolute;
background: url(‘//i.imgur.com/TxzC70f.png’) no-repeat;
cursor: pointer;
}
</style>

 

You can see my solution on action here

Now, the page only downloads ~60KB before playing the video. I’ve reduces the downloads by 7.5% and one-third request (previous request was 23!)