Arrow of tachometre in red zone. Car dashboard. Accelerating.

More Optimization Techniques for Improving Website Speed

Web performance is an essential element of the user experience. In thefirst partof this series, I talked about a method for automating some tasks related to web performance optimization. Here, in the second part of the series, we will go over some slightly moreadvanced techniquesfor improving front-end web performance.

This is what we will talk about:Optimizing the HTML structure

  • Referencing JavaScript and CSS files at the bottom
  • Dealing with flash of unstyled content (FOUC)
  • Inlining CSS and JavaScript

Server configuration

  • Browser caching
  • How long should files be cached?
  • How to override caching
  • Data compression

After applying all of theseoptimizationson my site, I was able to get a perfect (100/100)PageSpeed Insightsscore for both mobile and desktop web performance analyses.

Optimizing the HTML Structure

For a long time, I thought that my external CSS and JavaScript references should be inside thetags. Referencing JS and CSS resources at the start of HTML documents made sense to me because I need this stuff for my web pages to look and function properly.

But havingscriptandlinkelements at the start of the HTML document can block the render of the page, meaning the browser won’t process and display any subsequent HTML element until the resources have been downloaded and processed. Many JavaScript files, especially those written with asynchronous programming in mind, often don’t need to be referenced inside thetag and can be loaded further down the HTML document so that they don’t block the browser from rendering the page content. Referencing CSS files towards the end of the HTML document is a little bit trickier.

That’s because when you load CSS files at the end of the document, the user might start seeing the page content without any styles because the style rules from the external stylesheet haven’t been loaded and processed yet. This situation is calledflash of unstyled content(FOUC).

Referencing JavaScript and CSS Files at the Bottom

Whenever possible, we should reference external resources at the bottom of the document.

Just before the closingbodytag.

  ... 
...

Dealing with Flash of Unstyled Content

To address the FOUC, what I’ve done is give thebodyelement an inline style attribute of 0% opacity.

style=opacity:0>

Then, in my external stylesheet, I reset thebodyelement back to 100% opacity.

body {opacity: 1 !important;}

When the external stylesheet has been loaded and processed, the content will be displayed.

The issue with this technique is if there was a server failure that prevents the CSS file from being downloaded, the user would just see a blank page because of the inline style attribute given to thebodyelement.

Inlining CSS and JavaScript

You can also include CSS style rules within