Problem

Sometimes you update your stylesheet and and you don’t see any effects on the browser as if you had never mad any change.

Cause

The main reason behind this is that browsers download assets Images | Stylesheets | Javascript Files and cache it in the user machine, therefore whenever the browser detects the same url for the asset it will load it from the user’s machine instead of the server.

Why browser do this?

To reduce number of sent requests to the server and also to make the website runs faster as the lower the browser sends requests the faster it will load the website.

Solution

A very simple yet powerful solution is to trick the browser by telling him this is a new link so please download it.

Add at the end of your link a query string with any random value each time you want the browser to redownload the stylesheet file.

Example

<link rel="stylesheet" href="my-style.css?v=1.0"

This will tell the browser to send a request to the server to get the file my-style.css?v=1.0 while this is just the same stylesheet but the browser doesn’t know this yet.

Reforce download the stylesheet while development

If you’re using a server side language like PHP, you can generate a random string each time so the browser will always download the latest version from the server instead of the cache.

<link rel="stylesheet" href="my-style.css?v=<?php echo mt_rand(); ?>"

The mt_rand function will generate a new random number for each time a request is sent to serve the page that loads that stylesheet.

Conclusion

Caching stylesheets and javascripts by the browsers can be a pain for the developers as they may not consider that the update they made is not done and the real reason is because of the browser cache.

The method listed above will reduce this issue from being happened once again.

Happy Coding.

CSS#CSSPHP#PHPJAVASCRIPT#JAVASCRIPT