How to improve web performance
Tags: webdev, performance, javascript, frontend
Published: 2024-05-10 17:40:55


Welcome, you are 1 scroll away to improve your website performance.

Improving website page scores is crucial for achieving higher search result rankings, given Google's integration of Core Web Vitals into its algorithm. Therefore, optimizing Core Web Vitals is paramount for successful online reach and maintaining competitiveness in today's digital landscape.

**What is Web Vitals?**
Web Vitals are a set of key performance metrics that Google uses to measure and quantify user experience on the website.


![Tabular representation of the Core Web Vitals](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxvnsefnkivvy2b84i5g.png)


### 1. Start with optimising on Images

__Utilize CDN (Content Delivery Network) like [Cloudinary](https://cloudinary.com/) or [AWS CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) S3:__ CDN helps in delivering images faster by caching them on servers located closer to the user. This reduces latency and improves page loading speed. <br/>


**Compress Images:** Reduce file size while maintaining quality using image compression tools like [TinyPNG](https://tinypng.com/) or [ImageOptim](https://imageoptim.com/mac).
Also, you can use Figma plugin: [ExportX](https://www.figma.com/community/plugin/1301958586584763919/exportx-all-in-one-figma-plugin-for-image-compression-upload#:~:text=Compression%20%26%20Upload%20%7C%20Figma-,ExportX%20%2D%20All%2Din%2Done%20Figma,Plugin%20for%20Image%20Compression%20%26%20Upload&text=In%20version%201.,instead%20uses%20WebAssembly%20compression%20locally)  

**Use WebP Format for Images:** WebP is an image format developed by Google that provides superior compression and quality compared to JPEG and PNG. Using WebP can significantly reduce image file sizes, resulting in faster load times.

    

**Lazy Loading:** Defer loading of off-screen images until they are needed using lazy loading techniques. Utilize libraries like [lazysizes](https://github.com/aFarkas/lazysizes) or native browser lazy loading attributes.

```
<img loading="lazy" src="https:/cdn/url" />
```

Read more on: how to lazy load using [lazysizes](https://web.dev/articles/codelab-use-lazysizes-to-lazyload-images)

Note: First fold images should be eagerly loaded instead of lazy loading, since that way will improve first contentful paint (FCP)

```
<img loading="eager" src="https:/cdn/url" />
```

**Use srcset attribute:** 
You can ensure that users receive images optimized for their device's capabilities, leading to faster load times, reduced bandwidth usage, and overall improved performance.


```
  <picture>
    <source media="(max-width: 768px)" srcset="https://cdn/images/MobileImage.webp" />
        <img loading="lazy" alt=""
        src="https://cdn/images/desktopImage.webp" class="imgWidthHeight"/>
 </picture>

```

- The picture tag element allows us to define multiple sources for an image.
- Within each source element, the srcset attribute specifies multiple image sources with different resolutions, each followed by its corresponding width descriptor (e.g., 800w, 1200w, etc.).
- The _sizes_ attribute specifies the width of the image to use in different scenarios based on the viewport size.
- The _media_ attribute within the first <source> element specifies a media query to conditionally load the image based on the viewport width.
- The img element inside the picture tag element serves as a fallback for browsers that do not support the picture tag element or srcset attribute. It specifies the default image source.

Note: please use srcset with a picture tag (as shown above example) because in some versions of ios image tag with only srcset doesn't work correctly. 
Read more: [If srcset not working as expected](https://stackoverflow.com/questions/28650327/responsive-images-srcset-not-working)

**Set Fetch Priority:** Prioritize image loading by setting fetch priorities, ensuring that critical images load first. This enhances user experience, especially for above-the-fold content. Fetch priority should be high for the first-fold-content. 

**Specify Width and Height Attributes:** Including width and height attributes in image tags helps browsers allocate space for images while the page is loading. This prevents layout shifts and improves visual stability, particularly important for reducing Cumulative Layout Shift (CLS).

**Provide Aspect Ratio property:** Specifying width and height or at least aspect ratio for images is essential for improving CLS. When images without specified dimensions load, they can cause layout shifts as the browser adjusts the layout to accommodate the images. 

Note: only giving aspect-ratio css property to your image will not fix the layout shift, you need to specify width and height attribute of the image. 

[Aspect ratio](https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio) property is very useful in case were you want to adjust the width and height according to viewport.

```
width: 100%; height: auto; aspect-ratio: 16 / 9; 
```
In short, use aspect-ratio were you cannot define fixed width and height to the image.

To understand more on [how to fix Cumulative Layout shift CLS](https://www.smashingmagazine.com/2021/06/how-to-fix-cumulative-layout-shift-issues/)

---

### 2. Think in terms of Users:
 If your majority of users are mobile user then optimize using **mobile first approach**, i.e., prioritizing content and features that are essential for the mobile users, you should avoid unnecessary bloat and improve overall website performance.

---

### 3. Defer Scripts and Preload Styles:

Defer loading JavaScript means delaying the execution of non-critical JavaScript until after the page has finished loading. 

This allows the browser to render the page content without being blocked by JavaScript execution, resulting in faster initial page load times.

Preloading critical stylesheets/fonts ensures that essential CSS files are loaded as early as possible, preventing render-blocking delays. This can improve the perceived performance of the website by ensuring that the styling is applied quickly.

Combining deferred script loading with preloading critical stylesheets optimizes the loading sequence of resources, prioritizing essential assets and improving overall website performance.

---

### 4. Minify HTML, CSS, and JS:
Minification is the process of removing unnecessary characters and whitespace from HTML, CSS, and JavaScript files, reducing their file size. This results in faster download times and reduced bandwidth usage.

There are couple of ways and tools which can be used 

- Build time minification tools are [Gulp](https://medium.com/devux/minifying-your-css-js-html-files-using-gulp-2113d7fcbd16), [terser](https://github.com/terser/terser) etc.
- Runtime packages which can be used are [cleanCss](https://www.npmjs.com/package/clean-css), [uglifyJs](https://www.npmjs.com/package/uglify-js)

---

### 5. Keep DOM Size Small:

The Document Object Model (DOM) represents the structure of a web page and is manipulated by JavaScript to dynamically update content and respond to user interactions.

Keeping your DOM size small means minimizing the number of DOM elements and the complexity of the DOM tree. This reduces the memory consumption and improves the rendering performance, especially on mobile devices with limited resources.

Avoid unnecessary nesting of HTML elements, optimize CSS selectors to minimize DOM traversal, and use JavaScript judiciously to avoid excessive DOM manipulation.

Large DOM sizes can lead to slower rendering times, increased memory usage, and potential performance issues, especially on older devices or browsers.


---


### Conclusion: 
We've discussed all the optimization techniques to increase the website performance. 

Bonus Tip: we should know our codebase very well, sometimes deprecated, unused and many times unnecessary files are getting loaded which can hamper the web performance.

Feel free to add some more points in the comments.

Please leave questions, if any and like, if you found it helpful.